/// <summary>
/// 快速排序
/// </summary>
/// <param name="arr">排序的数组</param>
/// <param name="low">设置下标开始位置,向右找</param>
/// <param name="high">设置下标结束位置,向左找</param>
private static void Sort(int[] arr, int low, int high)
{
if (low >= high) return;
//完成一次单元排序
int index = QuickSort(arr, low, high);
//递归调用,对左边部分的数组进行单元排序
Sort(arr, low, index - 1);
//递归调用,对右边部分的数组进行单元排序
Sort(arr, index + 1, high);
}
/// <summary>
/// 单元排序
/// </summary>
/// <param name="arr">排序的数组</param>
/// <param name="low">设置下标开始位置,向右找</param>
/// <param name="high">设置下标结束位置,向左找</param>
/// <returns>每次单元排序的停止下标</returns>
private static int QuickSort(int[] arr, int low, int high)
{
int key = arr[low];//基准数
while (low < high)
{
//从high往前找小于或等于key的值
while (low < high && arr[high] > key)
{
high--;
}
//比key小开等的放左边
arr[low] = arr[high];
//从low往后找大于key的值
while (low < high && arr[low] <= key)
{
low++;
}
//比key大的放右边
arr[high] = arr[low];
}
//结束循环时,此时low等于high,左边都小于或等于key,右边都大于key。将key放在游标当前位置。
arr[low] = key;
return high;
}
int[] arr = { 23, 15, 21, 56, 90, 45, 23, 76, 34, 22, 2, 6, 4, 12, 78, 345};
Sort(arr, 0, arr.Length - 1);
foreach (var item in arr)
{
Console.WriteLine(item);
}
Console.Read();
转自:https://www.cnblogs.com/homeforhzw/p/6272439.html