Sorting and Searching Algorithms Practice
1. Sort Colors
Given a array nums containing elements representing red, white, and blue colors (denoted by integers 0, 1, and 2 respectively), sort the array in-place so that objects of the same color are adjacent and arranged in the order red, white, and blue.
The solution can be implemented using bubble sort:
void sortColors(int* nums, int numsSize) {
for (int i = 0; i < numsSize; i++) {
for (int j = 0; j < numsSize - i - 1; j++) {
if (nums[j] > nums[j + 1]) {
int temp = nums[j];
nums[j] = nums[j + 1];
nums[j + 1] = temp;
}
}
}
}
2. Search in 2D Matrix
Given a matrix where each row is sorted in non-decreasing order and the first element of each row is greater than the last element of the previous row, determine whether a given target value exists in the matrix.
A straightforwrad approach involves traversing all elements:
bool searchMatrix(int** matrix, int matrixSize, int* matrixColSize, int target) {
for (int i = 0; i < matrixSize; i++) {
for (int j = 0; j < *matrixColSize; j++) {
if (matrix[i][j] == target)
return true;
}
}
return false;
}
Alternatively, binary search can be used by treating the 2D matrix as a 1D array. The mapping from 1D index mid to 2D coordinates is defined as follows:
- Row index:
row = mid / totalColumns - Column index:
col = mid % totalColumns
Here's the implementation using binary search:
bool searchMatrix(int** matrix, int matrixSize, int* matrixColSize, int target) {
int left = 0;
int right = (*matrixColSize) * matrixSize - 1;
int mid;
while (left <= right) {
mid = left + (right - left + 1) / 2;
int row = mid / (*matrixColSize);
int col = mid % (*matrixColSize);
if (matrix[row][col] == target)
return true;
if (left >= right)
break;
if (matrix[row][col] < target)
left = mid;
else
right = mid - 1;
}
return false;
}