感觉义无反顾的再次在边界问题上纠结良久:
到底两边夹击的i和j 相遇之后返回pivot的操作如何处理?
两个极限情况的考虑:
1. i一路高歌到底,与j碰头
2.j顺流直下,直接到i
闲话不多说,上代码:
#include<stdlib.h>
#include <stdio.h>
/*
* Demo of how to quick sort an array
*
* Author: mmLiu
* Date : 2010_4_21
*/
void main(){
int getRandom();
void qSort(int a[],int low,int high);
//generate random array and print it
int a[20];
for(int i=0;i<20;i++){
a[i]=getRandom();
}
printf("befor sort\n");
for(int i=0;i<20;i++){
printf("%d\n",a[i]);
}
//sort the array and print the result
qSort(a,0,19);
printf("befor sort\n");
for(int i=0;i<20;i++){
printf("%d\n",a[i]);
}
getchar();
}
//quick sort
void qSort(int a[],int low,int high){
int partition(int a[],int low,int high);
if(low<high){
int pivot=partition(a,low,high);
//iterate
qSort(a,low,pivot-1);
qSort(a,pivot+1,high);
}
}
//seperate the array into 2 parts,smaller part and bigger part,return the pivot
int partition(int a[],int low,int high){
void swap(int a[],int i,int j);
int i=low+1;
int j=high;
while(i<j){
while(a[i]<a[low] && i<j){
i++;
}
while(a[j]>a[low] && i<j){
j--;
}
if(i<j){
swap(a,i,j);
}else if(i==j){
if(a[i]>=a[low]){
swap(a,i-1,low);
return i-1;
}else if(a[i]<a[low]){
swap(a,i,low);
return i;
}
}
}
}
//swap position in arrray
void swap(int a[],int i,int j){
int temp=a[i];
a[i]=a[j];
a[j]=temp;
}
//get random number
int getRandom(){
return 1+(int)(100.0*rand()/(RAND_MAX+1.0));
}