快速排序C#实现

快速排序是7大排序算法中最高效的算法,它在C++中的STL、java sdk 、.Net中都有实现。

它的算法时间复杂度为O(nlogn),它的原理是通过一趟排序将待排记录分割成独立的两部分,其中一部分记录的关键字均比另一部分记录的关键字小,则可分别对这两部分记录继续进行排序,以达到整个序列有序的目的。

具体C#代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Sort
{
    class Program
    {
       //快速排序
        static void quickSort(int[] arr, int low, int high)
        {
	        if (low < high) {
		        // 找寻基准数据的正确索引
		        int index = getIndex(arr, low, high);

		        // 进行迭代对index之前和之后的数组进行相同的操作使整个数组变成有序
		        quickSort(arr, 0, index - 1);
		        quickSort(arr, index + 1, high);
	        }
        }
       //选取枢轴,也是先选取当中的一个关键字,比如3,然后想办法把它放到一个位置,使它左边的值都比它小,右边的值都比它大,将这样的关键字称为枢轴。
       static int getIndex(int[] arr, int low, int high)
       {
	        // 基准数据
	        int tmp = arr[low];
	        while (low < high) {
		        // 当队尾的元素大于等于基准数据时,向前挪动high指针
		        while (low < high && arr[high] >= tmp) {
			        high--;
		        }
		        // 如果队尾元素小于tmp了,需要将其赋值给low
		        arr[low] = arr[high];
		        // 当队首元素小于等于tmp时,向前挪动low指针
		        while (low < high && arr[low] <= tmp) {
			        low++;
		        }
		        // 当队首元素大于tmp时,需要将其赋值给high
		        arr[high] = arr[low];

	        }
	        // 跳出循环时low和high相等,此时的low或high就是tmp的正确索引位置
	        // 由原理部分可以很清楚的知道low位置的值并不是tmp,所以需要将tmp赋值给arr[low]
	        arr[low] = tmp;
	        return low; // 返回tmp的正确位置
        }
        static void Main(string[] args)
        {
            int[] arr = { 1, 3, 2, 4, 0, 5, 6 };
            quickSort(arr,0,arr.Length-1);
            for (int i = 0; i < arr.Length; ++i) {
                Console.WriteLine(arr[i]);
            }
            Console.ReadKey();
        }
    }
}

以上代码在VS2017中运行通过。