HomeSoftware DevelopmentDiscover indices in a sorted Matrix the place a brand new quantity...

# Discover indices in a sorted Matrix the place a brand new quantity may be changed

Given a matrix arr[][] which is sorted by the growing variety of components and a quantity X, the duty is to seek out the place the place the enter integer may be changed with an current ingredient with out disturbing the order of the sorted components. The matrix is sorted in such a fashion that:

• Each row is sorted in growing order of components.
• Each single ingredient within the present row will likely be better than each single ingredient of the earlier row and smaller than each single ingredient of the subsequent row.

Examples:

Enter: arr[][] = { {1, 1, 3, 4, 5}, {6, 7, 8, 9, 10}, {11, 12, 13, 15, 16} }, X =  2
Output: 0 2
Clarification: Within the given matrix, X = 2 so 2 may be changed both with {0, 1} or {0, 2} as a result of alternative at these two positions doesn’t break the order of the sorted matrix.

Enter: arr[][] = { {1, 1, 3, 4, 5}, {6, 7, 8, 9, 10}, {11, 12, 13, 15, 16} }, X = 14
Output: 2 2
Clarification: The enter quantity is 14 so it might be both changed with 13 or 15 to take care of the sorted order.

Strategy: This may be solved with the next concept:

The strategy is to use the binary search for the optimum resolution.

Steps concerned within the implementation of code:

• Initialize l(low) as 0 and h(excessive) as (m*n)-1. Apply binary search utilizing a whereas loop the place l < h.
• Initialize mid(center) as (l+h)/2  and entry the center ingredient utilizing arr[mid/m][mid%m] .
• As soon as the binary search’s loop is over then return the indexes that are represented by mid.

Under is the implementation of the above strategy:

## C++

```// C++ code of the above strategy
#embrace <bits/stdc++.h>
utilizing namespace std;

// To seek out the index of changed ingredient
vector<int> findIndex(vector<vector<int> > arr, int quantity)
{

int l = 0, m = arr.dimension(), n = arr.dimension(), mid;
int h = m * n - 1;

// Whereas loop to do the binary search
whereas (l <= h) {

// Get the mid ingredient
mid = (l + h) / 2;

// If quantity itself is discovered
if (arr[mid / m][mid % m] == quantity) {
return { mid / m, mid % m };
}

else if (arr[mid / m][mid % m] < quantity) {
l = mid + 1;
}

else {
h = mid - 1;
}
}

// Return the index of
// changed ingredient
return { mid / m, mid % m };
}

// Driver code
int major()
{
vector<vector<int> > arr = { { 1, 1, 3, 4, 5 },
{ 6, 7, 8, 9, 10 },
{ 11, 12, 13, 15, 16 } };

// Perform name
vector<int> ans = findIndex(arr, 25);
cout << ans << " " << ans;

return 0;
}```

Time Complexity: O(logN)
Auxiliary Area: O(1)

RELATED ARTICLES