//快速排序的平均时间性能最快,有着广泛的应用,典型时UNIX系统库函数的qsort函数,但在数据基本有序的情况下,其时间性能最差;
//快速排序的基本思想是:任选序列中的一个元素,一般选第一个元素作为枢轴,用它和剩余的元素进行比较,将所有比他小的放在他的前面,比他大的元素放在后面,经过一趟排序后,以次元素为界,继续划分;一般从右开始比较,一直重复次过程,直至一部分中只剩下一个元素为止。但当元素有序时就退化为冒泡排序,时间复杂度为O(n2);一般情况下为nLOGn。
#include <stdio.h>
#include <stdlib.h>
int partition(int array[],int low,int high);
void quicksorthelp(int array[],int low,int high);
void quicksort(int array[],int number);
void swap(int *a, int *b);
int main()
{
int i,count;
printf("please input the number of your data:\n");
scanf("%d",&count);
int array[count];
printf("please input the number:\n");
for(i=0;i<count;i++)
scanf("%d",&array[i]);
printf("before the sort:\n");
for(i=0;i<count;i++)
printf("%d ",array[i]);
printf("\n");
quicksort(array,count);
printf("after sort:\n");
for(i=0;i<count;i++)
printf("%d ",array[i]);
printf("\n");
}
void swap(int *a,int *b)
{
int temp=*a;
*a=*b;
*b=temp;
}
int partition(int array[], int low , int high)
{
while(low < high)
{
while(low<high && array[high] >= array[low] )
high--;
swap(&array[low],&array[high]);
while(low < high && array[low]<= array[high])
low++;
swap(&array[low],&array[high]);
}
return low;
}
void quicksorthelp(int array[],int low ,int high)
{
if(low < high)
{
int privoLoc=partition(array,low,high);
quicksorthelp(array,low,privoLoc);
quicksorthelp(array,privoLoc+1,high);
}
}
void quicksort(int array[],int number)
{
quicksorthelp(array,0,number-1);
}
#include <iostream>
using namespace std;
void swap(int &a,int &b);
int position(int a[],int low,int high);
void quicksorthelp( int a[], int low, int high);
void quicksort(int a[],int n);
int main()
{
int number;
cout<<"请输入你的数组的个数:"<<endl;
cin>>number;
int a[number];
cout<<"请你输入你的数据:"<<endl;
for(int i=0;i<number;i++)
{
cin>>a[i];
}
cout<<"请确认你的数据:"<<endl;
for(int i=0;i<number;i++)
{
cout<<a[i]<<" ";
}
cout<<endl;
cout<<endl;
cout<<"排序后的顺序是"<< endl;
quicksort(a,number);
for(int i=0;i<number;i++)
{
cout<<a[i]<<" ";
}
}
void swap(int &a,int &b)
{
int temp;
temp=a;
a=b;
b=temp;
}
int position(int a[],int low,int high)
{
while(low<high)
{
while(low<high&& a[high]>=a[low])
{
high--;
}
swap(a[low],a[high]);
while(low<high&&a[low]<=a[high])
{
low++;
}
swap(a[low],a[high]);
}
return low;
}
void quicksorthelp( int a[], int low, int high)
{
if(low<high)
{
int key=position(a, low, high);
quicksorthelp(a,low,key-1);
quicksorthelp(a,key+1,high);
}
}
void quicksort(int a[],int n)
{
quicksorthelp(a,0,n-1);
}