快速排序以及二分查找的实现

#include <stdio.h>

int BinSearch(int a[],int left,int right,int key);//声明二分查找
void QuickSort(int a[],int left,int right);//声明快速排序

int main()
{
    int a[101];
    int i,n,key;
    printf("Please input total number:");
    scanf("%d",&n);
    printf("Now please input %d numbers:",n);
    for(i=0;i<n;i++)
    {
        scanf("%d",&a[i]);
    }
    QuickSort(a,0,n-1);
    printf("The array after QuickSort is :\n");
    for(i=0;i<n;i++)
    {
        printf("%d ",a[i]);
    }
    printf("\nPlaese input the number you want to search:");
    scanf("%d",&key);
    int order=BinSearch(a,0,n-1,key);
    if(order==-1)
    {
        printf("Can not find number %d\n",key);
    }
    else
    {
        printf("The order of number %d is %d\n",key,order+1);
    }
    return 0;

}


void QuickSort(int a[],int left,int right)
{
    int i=left,j=right;
    int key=a[left];
    if(left>right)
        return;
    while(i<j)
    {
        while(a[j]>=key&&i<j)
            j--;
        a[i]=a[j];
        while(a[i]<=key&&i<j)
            i++;
        a[j]=a[i];
    }
    a[i]=key;
    QuickSort(a,left,i-1);
    QuickSort(a,i+1,right);
}


int BinSearch(int a[],int left,int right,int key)
{
    int low=left,high=right,mid;
    if(left<=right)
    {
        mid=low+(high-low)/2;
        if(a[mid]==key)
        {
            return mid;
        }
        if(a[mid]>key)
        {
            return (BinSearch(a,low,mid-1,key));
        }
        else
        {
            return (BinSearch(a,mid+1,high,key));
        }
    }
    return -1;
}

posted on 2015-10-28 10:57  lie隼  阅读(158)  评论(0编辑  收藏  举报