算法-快速排序

快速排序是综合效率比较高的排序算法,最坏情况下复杂度比较高,但是平均性能比较好。并且它是原址排序,即无需创建新的临时数组。

快速排序使用分治思想,从数组中选取一个主元,然后将数组中的每一个数与主元比较,比主元小的数则放在主元元素左侧,比主元大的数则放在主元元素的右侧。

25 12 58 2 1 99 43 24

如上数组,我们取25为主元,将数组根据主元重新排序后如下:

12 2 1 24 25 58 99 43

然后我们采用分治法 以上次的主元这个数为中心,两边的数字按照上述规则排序(  将第1到第4个元素,第6到第8个元素按照排序)

1 2 12 24 25 43 58 99

核心算法如下:

 static void Main(string[] args)
        {
            int[] numbers = new int[] { 10,41,52,26,38,57,9,49}; 
            GetSort(numbers, 0, numbers.Length - 1);
}

//快速排序
        public void GetSort(int[] nums, int left, int right)
        {
            if (left < right)
            { 
                int center = left;//获取主元索引
                int key = nums[left];//获取主元数值
                for (int index = left + 1; index <= right; index++)
                {
                    if (nums[index] <= key)//小于主元则放置到数组第一位,其他数组往后移动一位
                    {
                        int temp = nums[index];
                        for (int j = index; j > left; j--)
                        {
                            nums[j] = nums[j - 1];
                        }
                        nums[left] = temp;
                        center++;//主元索引+1
                    } 
                } 
                GetSort(nums, left, center - 1);//排序前半段
                GetSort(nums, center + 1, right);//排序后半段
            }
        }
For循环算法
void quicksort(int[] nums, int left, int right)
        {
            if (left < right)
            {
                int key = nums[left];//获取主元数值
                int low = left;//获取下标
                int high = right;//获取上标
                while (low < high)
                {
                    while (low < high && nums[high] > key)
                    {
                        high--;
                    }
                    nums[low] = nums[high];
                    while (low < high && nums[low] < key)
                    {
                        low++;
                    }
                    nums[high] = nums[low];
                }
                nums[low] = key;
                quicksort(nums, left, low - 1);
                quicksort(nums, low + 1, right);
            }
        }
While循环算法

如上是应用for循环和while循环实现快速排序的方法,思想都是一样的。

其实快速排序在实际使用中很多变招,比如随机抽样,结合其他排序算法在粒度较小的子数组中进行排序等,具体可参照实际使用环境。



 

原文地址:https://www.cnblogs.com/qyzBlog/p/4223186.html