CC-16 : Search number in sorted matrix.
Description:
Given an input number and sorted matrix of numbers, find the number in the array.
Test cases and expected outputs:
| Input Parameters | Expected outputs |
|---|---|
| The sorted matrix : 7,8,10,11, 19,29,33,40, 52,61,74,81, |
Element: 33 found ? true Element: 64 found ? false |
Pseudocode:
searchInSortedMatrix(nums[][], toSearch):
| Integer matrix named nums and integer named toSearch to be searched are received as input parameters. |
| Set integer variable rows to nums.length. |
| Set integer variable cols to nums[0].length. |
| Set integer variable firstIdx to zero, we will use this variable to check the first index of partition in which are searching for required integer. |
| Set integer variable lastIdx to rows*cols-1, we will use this variable to check the last index of partition in which are searching for required integer. |
| Initialize integer variables named row and col. |
| While (firstIdx <= lastIdx) do the following steps:
Set integer variable midIdx to (lastIdx-firstIdx)/2. We will use midIdx to partition the array into 2 partitions.
Set row to midIdx/cols.
Set col to mid%cols.
If (nums[row][col] >= toSearch) :
Set lastIdx to midIdx.
Else:
Set firstIdx to midIdx+1.
|
| Set row to firstIdx/cols. |
| Set col to firstIdx%cols. |
| If (nums[row][col] == toSearch) :
Return true as we have found the required number in the input matrix.
|
| Else :
Return false, as required number does not exist in the input matrix.
|
Code:
public boolean searchInSortedMatrix(int[][] nums, int toSearch){
int rows=nums.length;
int cols=nums[0].length;
int firstIdx=0;
int lastIdx=rows*cols-1;
int row, col;
while (firstIdx < lastIdx) {
int midIdx=(lastIdx+firstIdx)/2;
row=midIdx / cols;
col=midIdx % cols;
if (nums[row][col]>=toSearch) {
lastIdx=midIdx;
} else {
firstIdx=midIdx+1;
}
}
row=firstIdx / cols;
col=firstIdx % cols;
int findIdx;
if (nums[row][col]==toSearch) {
return true;
}else {
return false;
}
}
Click here to download and run code and test cases !
| About Us | Privacy Policy | Contact us |