快速排序的基本思想是:通过一趟排序将要排序的数据分割成独立的两部分:分割点左边都是比它小的数,右边都是比它大的数。
然后再按此方法对这两部分数据分别进行快速排序,整个排序过程可以递归进行,以此达到整个数据变成有序序列。
def QuickSort(input_list,left,right):
def division(input_list,left,right):
base=input_list[left]
while left<right:
while left<right and input_list[right]>=base:
right-=1
input_list[left]=input_list[right]
while left<right and input_list[left]<base:
left+=1
input_list[right]=input_list[left]
input_list[left]=base
return left
if(left<right):
base_index=division(input_list,left,right)
QuickSort(input_list,left,base_index-1)
QuickSort(input_list,base_index+1,right)
if __name__=='__main__':
input_list=[6,4,8,9,2,3,1]
print('排序前',input_list)
sorted_list=QuickSort(input_list,0,len(input_list)-1)
print('排序后',input_list)
def quickSort2(a, L, R):
i = L
j = R
povit = a[(L + R) // 2]
while i < j:
while a[i] < povit: i += 1;
while a[j] > povit: j -= 1;
if i <=j:
temp = a[i]
a[i] = a[j]
a[j] = temp;
i+=1
j-=1
if L < j: quickSort(a, L, j -1);
if i < R: quickSort(a, i+1 , R);
def partition(a, i, j):
p = a[i]
m = i;
k = i + 1
while k <= j:
if (a[k] < p):
m += 1
temp = a[k]
a[k] = a[m]
a[m] = temp
k += 1
temp = a[i]
a[i] = a[m]
a[m] = temp
return m;
def quickSort1(a, low, high):
if (low < high):
m = partition(a, low, high)
quickSort(a, low, m - 1)
quickSort(a, m +1, high)