8.3.2快速排序

#include "stdafx.h"
#include 
<iostream.h>
#include 
<malloc.h>

int const count=8;

typedef 
struct 
{
    
int key;
}
records;

typedef records list[count
+1];

//此处没有使用书中的算法,书中的算法实现很繁索,且使用i,h,j,p,x一类的变量,使程序阅读更加吃力
//我实现的是严蔚敏版的数据结构中关于快速排序的算法,但书中的算法和这个思路是一致的,不过在于一些判断的时候方法有些不同,也没有这个算法巧妙
//快排算法最核心的思路就是,在一个排序数据中,取一个值,然后将小于它的数组项放在左面,将大于它的数组项放在它的右边,
//而这个值就是中值,然后分别再对分开的两部分再次调用排序算法,直至排序完成.
//r:排序的数组   low:排序区域中小的索引   high:排序区域中大的索引     return:分割两部分的中点索引
int Partition(list & r,int low,int high)
{
    r[
0].key=r[low].key;
    
while(low<high)
    
{
        
while(low<high && r[high].key>=r[0].key)
        
{
            high
--;
        }

        
//这里覆盖了low的值,这个值在首次的时候被r[0]所复制,在其它的时候,这个值属于在上次循环时确定的可以存放大于"枢轴值"的点位置
        r[low].key=r[high].key;
        
while(low<high && r[low].key<=r[0].key)
        
{
            low
++;
        }

        
//这里覆盖了high的值,这个值是在上面的循环中确定的可以存放小于"枢轴值"的点的位置
        r[high].key=r[low].key;
    }

    r[low].key
=r[0].key;
    
return low;
}


//快速排序
void QuickSort(list & r,int low,int high)
{
    
if (low<high)
    
{
        
//得到中值的索引
        int pivotkey=Partition(r,low,high);
        
//递归排序此中值左边的数组项
        QuickSort(r,low,pivotkey-1);
        
//递归排序此中值右边的数组项
        QuickSort(r,pivotkey+1,high);
    }

}


void printList(list r)
{
    
for(int i=0;i<count;i++)
    
{
        
if (i==0)
        
{
            cout
<<r[i+1].key;
        }

        
else
        
{
            cout
<<","<<r[i+1].key;
        }

    }

    cout
<<endl;
}


int main(int argc, char* argv[])
{
    list r;
    
/*
    for(int i=0;i<count;i++)
    {
        cout<<"输入第"<<i+1<<"个主键";
        cin>>r[i+1].key;
    }
    
*/

    r[
1].key=70;
    r[
2].key=73;
    r[
3].key=69;
    r[
4].key=23;
    r[
5].key=93;
    r[
6].key=18;
    r[
7].key=11;
    r[
8].key=68;
    cout
<<"输入的序列为:"<<endl;
    printList(r);
    
    QuickSort(r,
1,count);

    cout
<<"快速排序后的序列为:"<<endl;
    printList(r);
    
return 0;
}

    
posted @ 2007-08-07 16:09  吴东雷  阅读(295)  评论(0编辑  收藏  举报