I'm coding saddleback search in a sorted 2D array in Java and weird things happen.
Algorithm has to find the first occurence of given k
element in an array (rows first, then columns). Then it should also show on which index given number was found.
I wrote saddleback algorithm iteratively and it works, but after recoding it as recursive - it does not.
For array
10 10 10 10 10 20 20 30 20 20 20 40
And k: 20
It outputs, that k cannot be found in given array.
Also - the algorithm has got to have lower complexity than O(n,m)^3, so any other algorithm tips will be apprecieated.
Here is my code:
static boolean RekPier(int tab[][], int i, int j, int m, int n, int k){
System.out.println(i + " " + j + " " + tab[i][j]);
if (tab[i][j] == k && i < m && j < n){
findex = i;
lindex = j;
return true;
}
else if((tab[i][j] > k || tab[i][n-1] < k) && (i < m && j < n)){
int i1 = i+1;
if(i1 == m) return false;
RekPier(tab, i1, 0, m, n, k);
}
else if (i < m && j < n){
int j1 = j+1;
if(j1 == n) return false;
RekPier(tab, i, j1, m, n, k);
}
return false;
}
Your implementation had some errors but i modified the function like so:
static int RekPier(int arr[][], int i, int j,int M ,int N,int Value)
{
// If the entire column is traversed
if (j >= M)
return 0;
// If the entire row is traversed
if (i >= N)
return 1;
if(arr[i][j] == Value){
System.out.println("Row:" +i +'\t' +"Column:" +j);
}
// Recursive call to traverse the matrix in the Horizontal direction
if (RekPier(arr, i,j + 1, M, N,Value) == 1)
return 1;
// Recursive call for changing the Row of the matrix
return RekPier(arr,i + 1,0, M, N,Value);
}
Same complexity as yours
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.