Back
BinarySearch.cpp
Save
// BinarySearch.cpp #include
using namespace std; int b[100]; void MergeSort(int a[], int l, int r) { if (r > l) { int i, j; int m = (l + r) / 2; MergeSort(a, l, m); MergeSort(a, m + 1, r); for (i = m; i >= l; i--) b[i] = a[i]; for (j = m + 1; j <= r; j++) b[r + m + 1 - j] = a[j]; i = l; j = r; for (int k = l; k <= r; k++) { if (b[i] < b[j]) { a[k] = b[i]; i++; } else { a[k] = b[j]; j--; } } } } int BinarySearch(int a[], int n, int c) { int l = 0, r = n - 1, m; do { m = (l + r) / 2; if (a[m] > c) r = m - 1; if (a[m] < c) l = m + 1; } while (a[m] != c && l < r); if (a[m] == c) return m; else return -1; } int main() { int a[8] = {1, 3, 4, 9, 6, 7, 5, 4}; MergeSort(a, 0, 7); for (int i = 0; i < 8; i++) cout << a[i] << " "; cout << endl; cout << "Ket qua: " << BinarySearch(a, 8, 7); return 0; }