猥琐版
function quicksort(q) var list less, pivotList, greater if length(q) ≤ 1 { return q } else { select a pivot value pivot from q for each x in q except the pivot element if x < pivot then add x to less if x ≥ pivot then add x to greater add pivot to pivotList return concatenate(quicksort(less), pivotList, quicksort(greater)) }
public static List<int> quicksort(List<int> arr){ List<int> less = new List<int>(100); List<int> keyList = new List<int>(100); List<int> greater = new List<int>(100); if(arr.Count <= 1 || arr == null){ return arr; }else{ int key = arr[0]; for (int i = 0; i <= arr.Count - 1; i++) { if (arr[i] < key) { less.Add(arr[i]); } if(arr[i] > key){ greater.Add(arr[i]); } } keyList.Add(key); if(less != null && less.Count > 0) less = quicksort(less); if(greater != null && greater.Count > 0) greater = quicksort(greater); List<int> ret = new List<int>(); ret.AddRange(less); ret.AddRange(keyList); ret.AddRange(greater); return ret; } }
原地分割版
function partition(a, left, right, pivotIndex) pivotValue := a[pivotIndex] swap(a[pivotIndex], a[right]) // 把 pivot 移到結尾 storeIndex := left for i from left to right-1 if a[i] < pivotValue swap(a[storeIndex], a[i]) storeIndex := storeIndex + 1 swap(a[right], a[storeIndex]) // 把 pivot 移到它最後的地方 return storeIndex procedure quicksort(a, left, right) if right > left select a pivot value a[pivotIndex] pivotNewIndex := partition(a, left, right, pivotIndex) quicksort(a, left, pivotNewIndex-1) quicksort(a, pivotNewIndex+1, right)
public static void advQuickSort(ref List<int> arr, int left, int right){ if (right > left) { int key = arr[left]; int keyNewIndex = partition(ref arr, left, right, left); advQuickSort(ref arr, left, keyNewIndex - 1); advQuickSort(ref arr, keyNewIndex + 1, right); } } private static int partition(ref List<int> arr, int left, int right, int p) { int key = arr[p]; swap(ref arr,right, p); int storeIndex = left; for (int i = left ; i <= right; i++) { if (arr[i] < key) { swap(ref arr,storeIndex,i); ++storeIndex; } } swap(ref arr,right, storeIndex); return storeIndex; } public static void swap(ref List<int> arr, int a, int b){ int c= arr[a]; arr[a] = arr[b]; arr[b] = c; }