快速排序

#include<iostream>
using namespace std;
void quickSort(int a[],int,int);
int main()
{
    int array[]={34,65,12,43,67,5,78,10,3,70},k;
    int len=sizeof(array)/sizeof(int);
    cout<<"The orginal arrayare:"<<endl;
    for(k=0;k<len;k++)
        cout<<array[k]<<",";
    cout<<endl;
    quickSort(array,0,len-1);
    cout<<"The sorted arrayare:"<<endl;
    for(k=0;k<len;k++)
        cout<<array[k]<<",";
    cout<<endl;
    system("pause");
    return 0;
}

void quickSort(int s[], int l, int r)
{
    if (l< r)
    {
        int i = l, j = r, x = s[l];
        while (i < j)
        {
            while(i < j && s[j]>= x) // 从右向左找第一个小于x的数
                j--;
            if(i < j)
                s[i++] = s[j];
            while(i < j && s[i]< x) // 从左向右找第一个大于等于x的数
                i++;
            if(i < j)
                s[j--] = s[i];
        }
        s[i] = x;
        quickSort(s, l, i - 1); // 递归调用
        quickSort(s, i + 1, r);
    }
}

来源:C++实现快速排序(源代码)

二分查找

#include <iostream>

using namespace std;

//非递归实现
int BinarySearch(int array[], int len, int value)
{
    if (array == NULL || len <= 0)
        return -1;

    int low = 0;
    int high = len - 1;
    while (low <= high)
    {
        int mid = low + (high - low) / 2;
        if (array[mid] == value)
            return mid;
        else if (array[mid] > value)
            high = mid - 1;
        else
            low = mid + 1;
    }

    return -1;
}
//递归实现
int BinarySearch_Recursive(int array[], int low, int high, int value)
{
    if (low > high)
        return -1;
    int mid = low + (high - low) / 2;
    if (array[mid] == value)
        return mid;
    else if (array[mid] > value)
        return BinarySearch_Recursive(array, low, mid - 1, value);
    else
        return BinarySearch_Recursive(array, mid + 1, high, value);

}

int main(int argc, char *argv[])
{
    int i, j;
    int arr[10];
    for (i = 0; i < 10; i++)
    {
        arr[i] = i * 2;
    }
    cout << "Input the search number:";
    cin >> j;
    int location = BinarySearch(arr, 10, j);
    if (location != -1)
        cout << "Exist1:" << location << endl;
    else
        cout << "Not existed in array!" << endl;
    location = BinarySearch_Recursive(arr, 0, 9, j);
    if (location != -1)
        cout << "Exist2:" << location << endl;
    else
        cout << "Not existed in array!" << endl;
    system("pause");
    return 0;
}
01-20 19:59