//quickSort.cpp
/*
快速排序用到分治思想,为原址排序,不需要进行merge操作
第一步:分解:数组A[p...r]被划分为两个子数组A[p...q]和A[q+1...r],
使得A[p...q-1]中元素均小于A[r],A[q+1...r]中元素均大于等于A[r]
第二步:解决:通过递归调用快速排序,对子数组A[p...q-1]和A[q+1...r]进行排序
第三步:合并:因为子数组都是原址的,故不需要进行合并操作,数组A[p...r]已经有序
*/
#include <iostream>
#include <ctime>
#include <cstdlib>
#define NUMBER 20
using namespace std;
void quickSort(int *,int,int);
int partition(int *,int,int);//将数组划分为两部分
void exchange(int *,int *);
void print(int *str,int);
int main()
{
srand(unsigned(time(NULL)));
int A[NUMBER+1] = {0};
for(int i=1;i<=NUMBER;i++)
A[i] = rand()%101;//产生0到100之间的随机数
cout << "before quickSort,the array is:" << endl;
print(A,NUMBER);
quickSort(A,1,NUMBER);
cout << "after quickSort,the array is:" << endl;
print(A,NUMBER);
system("pause >> cout");
return 0;
}
//在数组中对str[p...r]进行快速排序
void quickSort(int *str,int p,int r)
{
if(p<r)
{
int q = partition(str,p,r);
quickSort(str,p,q-1);
quickSort(str,q+1,r);
}
}
int partition(int *str,int p,int r)
{
int i = p-1;
for(int j=p;j<r;j++)
{
if(str[j]<str[r])
{
i = i + 1;
exchange(&str[i],&str[j]);
}
}
exchange(&str[i+1],&str[r]);
return i+1;
}
void exchange(int *x,int *y)
{
int temp = *x;
*x = *y;
*y = temp;
}
void print(int *str,int num)
{
for(int i=1;i<=num;i++)
{
cout << " " << str[i];
}
cout << endl;
}
快速排序
最新推荐文章于 2023-12-01 23:14:38 发布