在众多的排序算法中,快速排序由于有较好的性能(时间复杂度O(NlogN),优于常见的排序算法),且算法编码难度较小,常在工程实践和招聘中使用或考察。这里手撸并上传了一个快速排序算法的C#实现。主要参考了Wiki 百科的“快速排序”,以及严蔚敏老师《数据结构》一书对快速排序的讲解。源码如下:
static void Main(string[] args)
{
int[] numbers = { 8, 3, 2, 4, 7, 6, 5 };
// 输出未排序数组
for (int i = 0; i < numbers.Length; i++)
{
Console.Write(numbers[i] + " ");
}
// 对该数组进行排序
QuickSort(numbers, 0, numbers.Length - 1);
// 输出已排序数组
Console.Write("\n--------------------------\n");
for (int i = 0; i < numbers.Length; i++)
{
Console.Write(numbers[i] + " ");
}
}
static void QuickSort(int[] numbers, int start, int end)
{
if (numbers == null || numbers.Length <= 0)
{
return;
}
if (start < 0 || end < 0 || start >= end)
{
return;
}
int pivort = start;
int mid = Partition(numbers, start, end, pivort);// mid 已经定位
QuickSort(numbers, start, mid - 1);
QuickSort(numbers, mid + 1, end);
}
static int Partition(int[] numbers, int start, int end, int pivort)
{
int pivortValue = numbers[pivort];
// 置换在数组中位置
Swap(numbers, end, pivort);
int storeIndex = start;
// 执行分割操作
for (int i = start; i <= end - 1; i++)
{
if (numbers[i] < pivortValue)
{
Swap(numbers, i, storeIndex);
storeIndex++;
}
}
Swap(numbers, storeIndex, end);
return storeIndex;
}
static void Swap(int[] array, int indexX, int indexY)
{
int temp = array[indexX];
array[indexX] = array[indexY];
array[indexY] = temp;
}
更多快速排序学习可参考 https://blog.csdn.net/wangxufa/article/details/121732098