随机快速排序算法是对快速算法的一种优化,本质没什么区别,随机快速排序的最坏情况就是和快速排序一样。
上代码:
- // Randomizde_QuickSort.cpp : 定义控制台应用程序的入口点。
- //
- #include "stdafx.h"
- #include<iostream>
- #include<ctime>
- using namespace std;
- /*函数声明*/
- void Randomize_QuickSort(int *A,int p,int r); //随机快速排序
- int Randomize_Partition(int *A,int p,int r); //随机分治法
- int Partition(int *A,int p,int r); //分治法
- void Display(int *a,int size); //打印函数
- /*主函数*/
- int _tmain(int argc, _TCHAR* argv[])
- {
- int size,*a;
- while(1)
- {
- cout<<"输入字符串长度:"<<endl;
- cin>>size;
- if(size > 0) {
- cout<<"请输入"<<size<<"个待排序数字:"<<endl;
- a = (int*)malloc(size*sizeof(int)); //a = new int [size];
- for(int i=0; i<size; i++) //输入数组
- {
- cin>>a[i];
- }
- Randomize_QuickSort(a,0,size-1); //调用快速排序函数
- }
- else
- cout<<"输入长度错误!"<<endl;
- Display(a,size); //打印数组
- }
- return 0;
- }
- /*函数定义*/
- void Randomize_QuickSort(int *A,int p,int r) //随机快速排序
- {
- int q;
- if(p<r) //如果p 小于等于 r 那么就程序不执行
- {
- q = Randomize_Partition(A,p,r); //调用随机分治法 找到q的值
- Randomize_QuickSort(A,p,q-1);
- Randomize_QuickSort(A,q+1,r);
- }
- }
- int Randomize_Partition(int *A,int p,int r) //随机分治法
- {
- int i,temp;
- srand(time(0)); /*设置种子,并生成伪随机序列*/
- i = p+(int)((r-p+1)*rand()/(RAND_MAX+1.0));
- temp = A[r]; //exchange
- A[r] = A[i];
- A[i] = temp;
- return Partition(A,p,r); //返回q值
- }
- int Partition(int *A,int p,int r) //分治法
- {
- int x,i,j,temp;
- x = A[r]; //将最后一个值保存在x中
- i = p-1; //开始的时候将i 移动到数组的外面
- for( j=p; j<=r-1; j++)
- {
- if(A[j]<=x)
- {
- i +=1;
- temp = A[i]; //exchange
- A[i] = A[j];
- A[j] = temp;
- }
- }
- temp = A[i+1]; //exchange
- A[i+1] = A[r];
- A[r] = temp;
- return i+1; //返回q值
- }
- void Display(int *a,int size) //打印函数
- {
- cout<<"排序结果为:"<<endl;
- for(int i=0; i<size; i++) //打印数组
- {
- cout<<a[i]<<" ";
- }
- cout<<endl<<endl;
- }
下面我们测试一组数组: 2 8 7 1 3 5 6 4