部份內容轉自坐在馬桶上看算法:快速排序和啊哈算法關於快速排序法爲何必定要從右邊開始的緣由。算法
快速排序的思想是選一個基準數,而後找到這個基準數在數組裏的位置,將大於它的放到它的右邊,小於它的放到它的左邊。數組
指針從兩邊向中間跑:ui
static void Main(string[] args) { int[] a = { 45, 80, 55, 40, 42, 85 }; quickSort(a, 0, a.Length - 1); foreach (var b in a) { Console.WriteLine(b.ToString()); } Console.ReadLine(); } static void quickSort(int[] array, int left, int right) { int i, j, temp; if (left > right) return; temp = array[left]; i = left; j = right; while (i != j) { while (array[j] >= array[left] && j > i) j--; while (array[i] <= array[left] && j > i) i++; temp = array[i]; array[i] = array[j]; array[j] = temp; } temp = array[i]; array[i] = array[left]; array[left] = temp; quickSort(array, left, i - 1); quickSort(array, i + 1, right); }
指針從左往右跑:spa
public static int Partition(int[] a, int p, int r) { int x = a[r]; int i = p; int temp; for (int j = p; j <= r; j++) { if (a[j] < x) { temp = a[j]; a[j] = a[i]; a[i] = temp; i++; } } temp = a[r]; a[r] = a[i]; a[i] = temp; return i; } public static void QuickSort(int[] a, int p, int r) { if (p < r) { int q = Partition(a, p, r); QuickSort(a, p, q - 1); QuickSort(a, q + 1, r); } } static void Main(String[] args) { int[] a = { 7, 10, 3, 5, 4, 6, 2, 8, 9, 9 }; QuickSort(a, 0, 9); for (int i = 0; i < a.Length; i++) Console.WriteLine(a[i].ToString()); Console.ReadLine(); }
快速排序詳解:.net
關於爲何要讓哨兵j先動:指針
while(arr[j]>=temp&&i<j){ j--; } while(arr[i]<=temp&&i<j){ i++; }
while(arr[j]>=temp&&i<j)