快速排序的思想:选择一个基准数(一般为左边第一个数),比它大的排在它的右边,比它小的排在右边,然后以这个数为基准线,对左右分而治之,重复上面的操作。
下面是从网友 那里盗的图,方便理解:
原图链接点我
代码:
using System;
using System.Collections;
using System.Collections.Generic;
namespace cchoop
{
class Program
{
static void Main(string[] args)
{
int[] arr = new int[] { 23, 45, 23, 22, 3, 4, 1, 0 };
QuickSort(arr, 0, arr.Length - 1);
foreach (var item in arr)
{
Console.Write(item + " ");
}
}
//3, 4, 1, 23, 45, 22
//挖坑法,左右分治
static void QuickSort(int[] arr, int low, int high)
{
if (low < high)
{
int index = QucikSortUnit(arr, low, high);
QuickSort(arr, low, index - 1);
QuickSort(arr, index + 1, high);
}
}
static int QucikSortUnit(int[] arr, int low, int high)
{
int temp = arr[low];
while (low < high)
{
while (low < high && arr[high] > temp)
{
high--;
}
arr[low] = arr[high];
while (low < high && arr[low] <= temp)
{
low++;
}
arr[high] = arr[low];
}
arr[low] = temp;
return low;
}
}
}