private static int binaricSearch(int[][] a, int num)
{
final int FIRST_COLUMN = 0;
int top = a.length -1 , bottom = 0, mid;
while(top >= bottom){
if(top == bottom)
return top;
mid = (top + bottom)/2;
if(num >= a[mid][FIRST_COLUMN] && num < a[mid][FIRST_COLUMN])
return mid;
else if(num > a[mid][FIRST_COLUMN])
bottom = mid + 1;
else if(num < a[mid][FIRST_COLUMN])
top = mid-1;
}
return top;
}
public static boolean findInMatrix(int[][] a, int num)
{
int indexRow = binaricSearch(a,num);
for(int j=0 ; j<a[0].length; j++ ) {
if (a[indexRow][j] == num)
return true;
}
return false;
}
public static void main(String[] args)
{
int[][] matrix = { {0,5,1,2,3},
{6,8,7,10,4},
{13,14,12,15,11},
{17,19,16,22,24}
};
for(int i=0; i < matrix.length; i++)
{
for(int j=0; j < matrix[i].length; j++)
{
System.out.print(matrix[i][j] + "\t");
}
System.out.print("\n");
}
int numToFind = 14;
System.out.println("\nThe Number: "+numToFind);
if(findInMatrix(matrix,numToFind) == true)
System.out.println("\n"+numToFind+" Found in the matrix!");
else
System.out.println("\n"+numToFind+" NOT Found in the matrix!");
}
* Прикрепленные выше реализации ^^
эй, я пытаюсь найти число в двумерном массиве с отсортированными столбцами в сложности времени выполнения O (n).
Но он находит только часть элементов.
Выходы:
Найдено, Для: 0, 5, 1, 2, 3, 8, 7, 10, 19, 16, 22 , 24
НЕ найдено, для: 4, 14, 12, 15, 11
ничего не печатать (я думаю, это застряло в l oop) Для: 6, 13