雪佛兰科鲁兹的通病:谁能用快速排序法排这几个数啊?

来源:百度文库 编辑:杭州交通信息网 时间:2024/05/07 06:14:02
由大到小5 6 8 7 1 2 3 4 8 9 5
一定要用快速排序法
坏了,忘提醒了,要用C编

算法的基本思想
快速排序的基本思想是基于分治策略的。对于输入的子序列L[p..r],如果规模足够小则直接进行排序(比如用前述的冒泡、选择、插入排序均可),否则分三步处理:

分解(Divide):将待排序列L[p..r]划分为两个非空子序列L[p..q]和L[q+1..r],使L[p..q]中任一元素的值不大于L[q+1..r]中任一元素的值。具体可通过这样的途径实现:在序列L[p..r]中选择数据元素L[q],经比较和移动后,L[q]将处于L[p..r]中间的适当位置,使得数据元素L[q]的值小于L[q+1..r]中任一元素的值。
递归求解(Conquer):通过递归调用快速排序算法,分别对L[p..q]和L[q+1..r]进行排序。
合并(Merge):由于对分解出的两个子序列的排序是就地进行的,所以在L[p..q]和L[q+1..r]都排好序后不需要执行任何计算L[p..r]就已排好序,即自然合并。

# include <iostream.h>
# include <conio.h>

# define MAXSIZE 20
typedef int RedType;

typedef struct //define SqList structure
{ RedType r[MAXSIZE+1];
int length;
}SqList;

int Partition(SqList &L,int low,int high) //Partition() sub-function
{ int pivotkey;
L.r[0]=L.r[low];
pivotkey=L.r[low];
while(low<high)
{ while(low<high&&L.r[high]>=pivotkey)
--high;
L.r[low]=L.r[high];
while(low<high&&L.r[low]<=pivotkey)
++low;
L.r[high]=L.r[low];
}
L.r[low]=L.r[0];
return (low);
} //Partition() end

void Qsort(SqList &L,int low,int high) //Qsort() sub-function
{ int pivotloc;
if(low<high)
{ pivotloc=Partition(L,low,high);
Qsort(L,low,pivotloc-1);
Qsort(L,pivotloc+1,high);
}
}

void QuickSort(SqList &L) //QuickSort() sub-function
{ Qsort(L,1,L.length); //call Qsort()
}

void main() //main() function
{ int i;
SqList L={{0,49,38,65,97,76,13,27,49},8};
cout<<endl<<endl<<"QuickSort.cpp";
cout<<endl<<"============="<<endl;
cout<<endl<<"The disordered : ";
for(i=1;i<=L.length;i++)
cout<<L.r[i]<<" ";
QuickSort(L); //call QuickSort()
cout<<endl<<"The sorted : ";
for(i=1;i<=L.length;i++)
cout<<L.r[i]<<" ";
cout<<endl<<endl<<"...OK!...";
getch();
} //main() end