Skip to content

Commit

Permalink
class 3
Browse files Browse the repository at this point in the history
  • Loading branch information
fdong-coursera committed Jun 30, 2015
1 parent 2260f05 commit 97111a4
Show file tree
Hide file tree
Showing 4 changed files with 92 additions and 0 deletions.
15 changes: 15 additions & 0 deletions class3/index_search.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
int indexSearch(int *array, int left, int right) {
if (left > right) {
// value not found
return -1;
}

int mid = right - (right - left) / 2;
if (array[mid] == mid) {
return mid;
} else if (array[mid] < mid) {
return indexSearch(array, mid + 1, right);
} else {
return indexSearch(array, left, mid - 1);
}
}
16 changes: 16 additions & 0 deletions class3/matrix_search.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
bool isElementInMatrix(int **matrix, int M, int N, int target) {
int row = 0;
int column = N - 1;

while (row < M && column >= 0) {
if (matrix[row][column] == target) {
return true;
} else if (matrix[row][column] < target) {
row++;
} else {
column--;
}
}
return false;
}

35 changes: 35 additions & 0 deletions class3/range_search.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
void searchRangeHelper(int array[], int left, int right, int target, int &begin, int &end) {
if (left > right) {
return;
}

int mid = right - (right - left) / 2;
if (array[mid] == target) {
if (mid < begin || begin == -1) {
begin = mid;
}
if (mid > end) {
end = mid;
}
searchRangeHelper(array, left, mid - 1, target, begin, end);
searchRangeHelper(array, mid + 1, right, target, begin, end);
}
else if (array[mid] < target) {
searchRangeHelper(array, mid + 1, right, target, begin, end);
}
else {
searchRangeHelper(array, left, mid - 1, target, begin, end);
}
}

vector<int> searchRange(int A[], int n, int target) {
int begin = -1, end = -1;

searchRangeHelper(A, 0, n - 1, target, begin, end);

vector<int> ans;
ans.push_back(begin);
ans.push_back(end);
return ans;
}

26 changes: 26 additions & 0 deletions class3/rotate_array_search.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
int rotated_binary_search(int A[], int N, int key) {
int L = 0;
int R = N - 1;

while (L <= R) {
// Avoid overflow, same as M=(L+R)/2
int M = L + ((R - L) >> 1);
if (A[M] == key) return M;

// the bottom half is sorted
if (A[L] <= A[M]) {
if (A[L] <= key && key < A[M])
R = M - 1;
else
L = M + 1;
}
// the upper half is sorted
else {
if (A[M] < key && key <= A[R])
L = M + 1;
else
R = M - 1;
}
}
return -1;
}

0 comments on commit 97111a4

Please sign in to comment.