2015/10/06写下的归并排序、快速排序、二分查找

归并排序

#include<iostream>
using namespace std;

void merge(int a[], int start, int middle, int end)
{
    int index1 = start;
    int index2 = middle + 1;
    int * buffer = new int[end - start + 1];
    int counter = 0;
    while(index1 <= middle && index2 <= end)
    {
        if(a[index1] <= a[index2])
            buffer[counter++] = a[index1++];
        else 
            buffer[counter++] = a[index2++];
    }

    if(index1 <= middle)
    {
        while(index1 <= middle)
            buffer[counter++] = a[index1++];
    }
    else
    {
        while(index2 <= end)
            buffer[counter++] = a[index2++];
    }

    for(int i = 0; i < counter; i++)
        a[start + i] = buffer[i];
}

void mergeSort(int a[], int start, int end)
{
    if(start == end)
        return;

    int middle = (start + end) / 2;
    mergeSort(a, start, middle);
    mergeSort(a, middle + 1, end);
    merge(a, start, middle, end);

    return;
}

int main()
{
    int a[] = {9, 10, 23, 14, 12};
    mergeSort(a, 0, sizeof(a) / sizeof(int) - 1);
    for(int i = 0; i < sizeof(a) / sizeof(int); i++)
        cout << a[i] << " ";
    getchar();
}

快速排序

#include<iostream>
using namespace std;

void swap(int *a, int *b) 
{
    int tmp = *a;
    *a = *b;
    *b = tmp;
}

int partition(int a[], int start, int end)
{
    int pivot = a[start];
    int left = start;
    int right = end;
    while(left < right)
    {
        while(left <= end && a[left] <= pivot) left++;
        while(right >= start && a[right] > pivot) right--;
        if(left < right) swap(&a[left], &a[right]);
    }
    int middle = right;
    swap(&a[start], &a[middle]);
    return right;
}

void quickSort(int a[], int start, int end)
{
    if(start == end)
        return;

    int index = partition(a, start, end);
    if(index > start)
        quickSort(a, start, index - 1);
    if(index < end)
        quickSort(a, index + 1, end);

    return;
}
int main()
{
    int a[] = {9, 10, 23, 14, 12}; 
    quickSort(a, 0, sizeof(a) / sizeof(int) - 1);
    for(int i = 0; i < sizeof(a) / sizeof(int); i++)
        cout << a[i] << " ";
    getchar();
}

二分查找

#include<iostream>
using namespace std;

int binarySearch(int a[], int start, int end, int target)
{
    while(start <= end)
    {
        int middle = (start + end) / 2;
        if(a[middle] == target)
            return middle;
        if(a[middle] > target)
            end = middle - 1;
        else
            start = middle + 1;
    }

    return 2147483647;//用2147483647表示没有找到
}

int main()
{
    int a[] = {9, 10, 23, 24, 32};
    int i = binarySearch(a, 0, sizeof(a) / sizeof(int) - 1, 32);
    cout << i << " ";
    getchar();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值