二分插入與二分查詢

qingyezhu發表於2013-10-08

 

/*
 * binarysort.cpp
 *
 *  Created on: 2013-10-8
 *      Author: wangzhu
 */

#include<cstdio>
#include<iostream>
using namespace std;
#define NMAX 1000
int arr[NMAX];
int binarySearch(int left, int right, int key) {
    while (left <= right) {
        int mid = left + (right - left) / 2;
        if (arr[mid] >= key) {
            right = mid - 1;
        } else {
            left = mid + 1;
        }
    }
    return left;
}
int main() {
    freopen("data.in", "r", stdin);
    int n;
    while (~scanf("%d", &n)) {
        for (int i = 0; i < n; i++) {
            scanf("%d", arr + i);
        }
        for (int i = 0; i < n; i++) {
            int temp = arr[i];
            int end = binarySearch(0, i, temp);
            for (int j = i - 1; j >= end; j--) {
                arr[j + 1] = arr[j];
            }
            arr[end] = temp;
        }
        for (int i = 0; i < n; i++) {
            if (i == n - 1) {
                printf("%d\n", arr[i]);
            } else {
                printf("%d ", arr[i]);
            }
        }
    }
    return 0;
}

 

相關文章