代码
from random import Random
def quick_sort(arr): if len(arr) > 1: qsort(arr,0,len(arr)-1) def qsort(arr,start,end): base = arr[start] pl = start + 1 pr = end while True: while arr[pl] > base: pl += 1 while arr[pr] < base: pr -= 1 if pl >= pr: break; arr[pl],arr[pr] = arr[pr],arr[pl] arr[start] = arr[pr] arr[pr] = base if(pr - 1 > start): qsort(arr,start,pr - 1) if(pl + 1 < end): qsort(arr,pr+1,end) r = Random() a = [] for i in range(20): a.append(r.randint(0,100)) print a quick_sort(a) print a 最后结果: [20, 84, 4, 12, 48, 91, 71, 84, 44, 43, 78, 46, 26, 50, 51, 90, 40, 7, 93, 62] 代码
/*
* ===================================================================================== * * Filename: quickSort.cpp * * Description: quick Sort method * * Version: 1.0 * Created: 11/25/2010 08:52:33 PM * Revision: none * Compiler: gcc * * Author: Archy Yu * Company: * * ===================================================================================== */ #include<stdio.h> void swap(int &i,int &j) { int k = i; i = j; j = k; } int Partition(int a[3],int left,int right) { int i = left; int j = right + 1; int tem = a[i]; while(true) { while(a[++i] < tem); while(a[--j] > tem); if(i >= j) break; swap(a[i],a[j]); } a[left] = a[j]; a[j] = tem; return j; } void QuickSort(int a[3],int left,int right) { if(left < right) { int part = Partition(a,left,right); QuickSort(a,left,part-1); QuickSort(a,part+1,right); } } int main() { int b[3] = {9,7,8}; QuickSort(b,0,3); for(int i=0;i<=2;i++) { printf("%d ",b[i]); } return 0; } |
|