快速排序浅解
#本教程主供本人自我复习所用,在此分享,希望别人也能有所收获。
首先来个python程序:
python2.7:
>>>def quickSort(L,low,high):
i=low
j=high
if i>=j:
return L
key=L[i]
while i<j:
while i<j and L[j]>=key:
j-=1
L[i]=L[j]
while i<j and L[i]<=key:
i+=1
L[j]=L[i]
L[i]=key
quickSort(L,low,i-1)
quickSort(L,i+1,high)
return L
>>>quickSort(range(10),0,9)
[0, 1,2, 3, 4, 5, 6, 7, 8, 9]
>>>quickSort(range(10)[::-1],0,9)
[0, 1,2, 3, 4, 5, 6, 7, 8, 9]
真的很巧妙,我试着讲讲:
c语言版:
void quicksort(int*a,int low,int high){
inti=low;
intj=high;
intkey=a[i];
while(i>=j){
return;
}
while(i<j){
while(i<j&&a[j]>=key){
j--;
}
a[i]=a[j];
while(i<j&&a[i]<=key){
i++;
}
a[j]=a[i];
}
a[i]=key;
quicksort(a,low,i-1);
quicksort(a,i+1,high);
return*a;
}