i want to find a "peak value" in an array (a value where a1 ai+1>...>an, ai being the peak value here). I am using divide and conquer for a more optimum solution here. For" 6 1 3 50 70 100 48", it will print "70 100 48 4" which is good ( 70 < 100 and 100 > 48) but it does not return Integer.toString(a[m]), it returns "Array has no peak". I tried removing string and working with int but i get the exact same issue.
public class Main {
public int n, a[];
void read() {
File file = new File("src/com/fmi/Vector.txt");
Scanner sc;
try {
sc = new Scanner(file);
int i = 0;
if (sc.hasNextInt()) {
n = sc.nextInt();
}
a = new int[n];
while (sc.hasNextInt()) {
int aux = sc.nextInt();
a[i] = aux;
i++;
}
} catch (FileNotFoundException e) {
System.out.println("File not found!");
}
}
String search(int p, int u) {
int m;
System.out.println(p + " " + u);
if (p == u) {
return "0";
} else {
m = (p + u) / 2;
System.out.println(a[m - 1] + " " + a[m] + " " + a[m + 1] + " " + m);
if (a[m - 1] < a[m] && a[m] > a[m + 1]) {
return Integer.toString(a[m]);
} else if (a[m - 1] < a[m] && a[m] < a[m + 1]) {
search(m, u);
} else if (a[m - 1] > a[m] && a[m] > a[m + 1]) {
search(p, m);
}
}
return "Array has no peak!";
}
void display() {
for (int i = 0; i < n; i++) {
System.out.print(a[i] + " ");
}
System.out.println(" ");
for (int i = 0; i < n; i++) {
System.out.print(i + " ");
}
}
public static void main(String[] args) {
Main obj = new Main();
obj.read();
System.out.println(obj.search(0, obj.n));
obj.display();
}
}
You're calling search but you're not doing anything with the result. You should do something like
return search(m,u);