男:約不約?
女:不約!
男:到底,約不約?
女:早說嘛,約!
Unity攤
一副很惆悵的樣子
using System;
namespace QuicklySortByJens
{
class MainClass
{
#region 建議::::::: 第一種快速排序的方法
//每次排序返回 下次進行分割排序的下標
public static int KeyValuePosition (int[] a, int low, int high)
{
//記錄數組的起始位置
int leftIndex = low;
//記錄數組的結束位置
int rightIndex = high;
//關鍵值, 通常為low下標所對應的元素值
int keyValue = a [low];
int temp;
//當左側動態下標值 小于 右側動態下標值時
while (leftIndex < rightIndex) {
//左側動態下標值增加 直到 找到比關鍵值大的位置為止
while (leftIndex < rightIndex && a [leftIndex] <= keyValue) {
//每循環一次, 左側動態下標值 向右走一個位置
leftIndex++;
}
//道理同上 直到 找到比關鍵值小的位置為止
while (leftIndex < rightIndex && a [rightIndex] > keyValue) {
rightIndex--;
}
//把左右側動態下標所在的元素值進行交換
if (leftIndex < rightIndex) {
temp = a [leftIndex];
a [leftIndex] = a [rightIndex];
a [rightIndex] = temp;
}
}
//將關鍵值賦值給一個變量
temp = keyValue;
//判斷關鍵值和相遇時的當前值的大小
//如果關鍵值 <= 相遇值, 就將相遇值前一個數與關鍵值 交換, 并返回前一個下標
//如果關鍵值 > 相遇值, 就直接將兩者交互, 并返回相遇時的當前下標
//返回 交換后 關鍵值 所在的下標
//以下標所在的位置進行分割, 遞歸調用
if (temp <= a [rightIndex]) {
//交換a[low]和a[rightIndex - 1]的值, 返回下標值
a [low] = a [rightIndex - 1];
a [rightIndex - 1] = temp;
return rightIndex - 1;
} else {
a [low] = a [rightIndex];
a [rightIndex] = temp;
return rightIndex;
}
}
static void Sort (int[] a, int low, int high)
{
try {
//記錄關鍵值的下標
int keyPosition;
//當傳遞的目標數組含有兩個或者兩個以上的元素時進行遞歸
if (low < high) {
//獲取關鍵值所在數組的下標
keyPosition = KeyValuePosition (a, low, high);
//以關鍵值下標為分界線, 以左邊的數值再進行上面的操作
//直到要參與排序的數據的個數為1, 即(log和high)的值相等時
//遞歸調用結束, 方法開始向外返出來
Sort (a, low, keyPosition - 1);
Sort (a, keyPosition + 1, high);
}
} catch (Exception ex) {
}
}
#endregion
#region 建議::::::: 第二種快速排序的方法
//http://developer.51cto.com/art/201403/430986.htm
static void QuickSortThree (int[] a, int left, int right)
{
int i, j, t, temp;
if (left > right)
return;
temp = a [left]; //temp中存的就是關鍵值
i = left;
j = right;
while (i != j) {
//順序很重要,要先從右邊開始找
//直到找到比關鍵值小的才停止
while (a [j] >= temp && i < j)
j--;
//再找右邊的
////直到找到比關鍵值大的才停止
while (a [i] <= temp && i < j)
i++;
//交換兩個數在數組中的位置
if (i < j) {
t = a [i];
a [i] = a [j];
a [j] = t;
}
}
//i = j時 ,最終將 關鍵值 與 相等的交換
a [left] = a [i];
a [i] = temp;
//分左右兩側進行遞歸排序
QuickSortThree (a, left, i - 1);//繼續處理左邊的,這里是一個遞歸的過程
QuickSortThree (a, i + 1, right);//繼續處理右邊的 ,這里是一個遞歸的過程
}
#endregion
#region 第三種快速排序的方法
static void QuickSort (int[]a, int left, int right)
{
if (left < right) {
int i = left;
int j = right;
int middle = a [(left + right) / 2];
while (true) {
while (i < right && a [i] < middle) {
i++;
}
while (j > 0 && a [j] > middle) {
j--;
}
if (i == j) {
break;
}
a [i] = a [i] + a [j];
a [j] = a [i] - a [j];
a [i] = a [i] - a [j];
if (a [i] == a [j]) {
j--;
}
}
QuickSort (a, left, i);
QuickSort (a, i + 1, right);
}
}
#endregion
public static void Main (string[] args)
{
int[] myArray = new int[]{ 53, 36, 18, 72, 20, 47, 56, 80 };
//Sort (myArray, 0, myArray.Length - 1);
QuickSortThree (myArray, 0, myArray.Length - 1);
//打印查看結果
foreach (var item in myArray) {
Console.WriteLine (item);
}
}
}
}
ps:比較懶了,直接貼代碼, 有興趣的可以參考一下 感謝這位帥哥得文章