快速排序(C#)
代碼實現:
public static void QuickSort(int[] a, int startIndex, int endIndex)<br /> {<br /> if (startIndex > endIndex)<br /> return;</p><p> int keyIndex = Partion(a, startIndex, endIndex);<br /> QuickSort(a, startIndex, keyIndex - 1);<br /> QuickSort(a, keyIndex + 1, endIndex);<br /> }</p><p> public static int Partion(int[] a, int startIndex, int endIndex)<br /> {<br /> int temp = 0;<br /> int leftMaxIndex = startIndex - 1;<br /> int key = a[endIndex];</p><p> for (int rightMaxIndex = startIndex; rightMaxIndex < endIndex; rightMaxIndex++)<br /> {<br /> if (a[rightMaxIndex] <= key)<br /> {<br /> // 小於等於key的放在左邊<br /> temp = a[leftMaxIndex + 1];<br /> a[leftMaxIndex + 1] = a[rightMaxIndex];<br /> a[rightMaxIndex] = temp;</p><p> leftMaxIndex++;<br /> }<br /> }</p><p> // 交換標兵<br /> temp = a[leftMaxIndex + 1];<br /> a[leftMaxIndex + 1] = a[endIndex];<br /> a[endIndex] = temp;</p><p> return leftMaxIndex + 1;<br /> }