快速排序

来源:互联网 发布:netflix知乎 编辑:程序博客网 时间:2024/05/16 23:57

/********************************************
Function: quick sort ,sort ascending
Create Date: 2010 6.25
By:          LiHong
********************************************/
#include<stdio.h>
#include <cstdlib>
void swap(int *temp1,int *temp2);
int split(int a[],int low,int high);
void quick_sort(int a[],int low,int high);

//The main function is for test
int main(){
int a[5];
a[0]=4, a[1]=5,a[2]=0,a[3]=4,a[4]=1;
printf("Before sort:");
for(int i=0;i<=4;i++){
 printf("%d ",a[i]);
}
printf("/nAfter sort:");
quick_sort(a,0,4);
for(int i=0;i<=4;i++){
 printf("%d ",a[i]);
}
printf("/n");
system("pause");
return 0;
}

int split(int a[],int low,int high){
int k,i=low;
int x=a[low];
for(k=low+1;k<=high;k++){
  if(a[k]<=x){
  i=i+1;
 if(i!=k){
 swap(&a[k],&a[i]); 
 }
  }
}
swap(&a[low],&a[i]);
return i;
}

void swap(int *temp1,int *temp2){
int temp;
temp=*temp1;
*temp1=*temp2;
*temp2=temp;
}
void quick_sort(int a[],int low,int high){
int k;
if(low<high){
k=split(a,low,high);
quick_sort(a,low,k-1);
quick_sort(a,k+1,high);
}
}

原创粉丝点击