快速排序实践

自己复习算法刚开始对于快速排序还是有点迷糊,后来多看了两遍终于搞明白怎么回事了,这里记录下

下面是实例代码,用代码注释来说明吧

void QuickSort(int* a, int left, int right)
{
    int ltemp = left;
    int rtemp = right;
    int f = a[left];

    while (ltemp < rtemp)
    {
     /*先从有变开始找,直到找到比key值小的值为止*/
while (ltemp < rtemp && a[rtemp] >= f) { --rtemp; } a[ltemp] = a[rtemp];/*在rtemp处挖个坑,把rtemp的值保存在ltemp位置上,rtemp暂时是空的坑*/     
     /*再从左到右扫描,直到找到比key值大的值为止*/
while (ltemp < rtemp && a[ltemp] <= f) { ++ltemp; } a[rtemp] = a[ltemp];/*这步是在ltemp处挖个坑(注意这地方的ltemp值已经改变),把ltemp的值保存在rtemp位置上,现在ltemp是空的坑*/
     /*把控制的坑填满,当前空置的坑是ltemp,所以把key值赋给ltemp*/
     a[ltemp]
= f;   
/*ltemp现在就相当于是key值,中间点了,后续的步骤是在以key值为中心,分别遍历左边和右边,直到所有的项都满足条件为止,下面的left,ltemp-1表示左半边 ,ltemp+1,right表示右半边*/
QuickSort(a, left, ltemp
- 1); QuickSort(a, ltemp + 1, right); } } #define MAX_LEN 5 int _tmain(int argc, _TCHAR* argv[]) { int *a = new int[MAX_LEN]; memset(a, 0, MAX_LEN); srand(time_t(NULL)); for (int i = 0; i < MAX_LEN; i++) { a[i] = rand() % 1000; printf("%d ", a[i]); } printf(" "); printf("开始排序 "); int tick = GetTickCount(); QuickSort(a, 0, MAX_LEN - 1); printf(" "); printf("排序用时:%d ", GetTickCount() - tick); for (int i = 0; i < MAX_LEN; i++) { printf("%d ", a[i]); } system("pause"); return 0; }

下面再加个备注,本来在写代码的时候最后面那部分还没有搞明白,写博客增加注释的时候就突然都搞明白了;看来看会还不算会,写出来才算会,哈哈。有空还是要出来多分享分享,加油加油

原文地址:https://www.cnblogs.com/davygeek/p/4376278.html