排序算法3:最常用的排序——快速排序

链接1:【坐在马桶上看算法】算法3:最常用的排序——快速排序
【啊哈!算法】系列

可以说是非常生动的了
啊哈磊博客园
链接2:C++简单排序算法之快速排序
1中的代码:

#include <stdio.h>
int a[101],n;//定义全局变量,这两个变量需要在子函数中使用
void quicksort(int left,int right)
{
    int i,j,t,temp;
    if(left>right)
       return;

    temp=a[left]; //temp中存的就是基准数
    i=left;
    j=right;
    while(i!=j)
    {
                   //顺序很重要,要先从右边开始找
                   while(a[j]>=temp && i<j)
                            j--;
                   //再找右边的
                   while(a[i]<=temp && i<j)
                            i++;
                   //交换两个数在数组中的位置
                   if(i<j)
                   {
                            t=a[i];
                            a[i]=a[j];
                            a[j]=t;
                   }
    }
    //最终将基准数归位
    a[left]=a[i];
    a[i]=temp;

    quicksort(left,i-1);//继续处理左边的,这里是一个递归的过程
    quicksort(i+1,right);//继续处理右边的 ,这里是一个递归的过程
}
int main()
{
    int i,j,t;
    //读入数据
    scanf("%d",&n);
    for(i=1;i<=n;i++)
           scanf("%d",&a[i]);
    quicksort(1,n); //快速排序调用

    //输出排序后的结果
    for(i=1;i<=n;i++)
        printf("%d ",a[i]);
    getchar();getchar();
    return 0;
}

2中的代码:

#include <iostream>
using namespace std;

void MySwap(int &a,int &b)
{
    if(a==b)
        return;
    a=a+b;
    b=a-b;
    a=a-b;
}

void print(int *p,int length)
{
    for(int i=0;i<length;i++)
    {
        cout<<p[i]<<" ";
    }
}

int getPartion(int *array, int low, int high)
{
    int key = array[low];
    while (low < high)
    {
        while (low < high && key <= array[high]) //如果array[high]大于键值,那么本就应该在键值右边
            high--;  //因此将high下标向前移动,直至找到比键值小的值,此时交换这两个值
        swap(array[low], array[high]);

        while (low < high && key >= array[low])
            low++;
        swap(array[low], array[high]);
    }
    return low;//返回key值的下标
}

void QuitSort(int *buf,int low,int high)
{
    if (low < high)
    {
        int key = getPartion(buf, low, high);

        QuitSort(buf, low, key - 1);
        QuitSort(buf, key + 1, high);
    }
}

int main(int argc, char *args[])
{
    int buf[10] = { 12, 4, 34, 6, 8, 65, 3, 2, 988, 45 };
    int m = sizeof(buf);
    cout << "排序前:" << endl;
    print(buf, sizeof(buf) / sizeof(int));

    QuitSort(buf, 0, sizeof(buf) / sizeof(int)-1);

    cout << "\n\n\n排序后:" << endl;
    print(buf, sizeof(buf) / sizeof(int));
    getchar();
    return 0;

}

猜你喜欢

转载自blog.csdn.net/zhenaoxi1077/article/details/80293345