zoukankan      html  css  js  c++  java
  • 排序:快速排序Quick Sort

    原理,通过一趟扫描将要排序的数据分割成独立的两部分,其中一部分的所有数据都比另外一部分的所有数据都要小,然后再按此方法对这两部分数据分别进行快速排序,整个排序过程可以递归进行,以此达到整个数据变成有序序列

    举个例子

    如无序数组[6 2 4 1 5 9]

    a),先把第一项[6]取出来,

    用[6]依次与其余项进行比较,

    如果比[6]小就放[6]前边,2 4 1 5都比[6]小,所以全部放到[6]前边

    如果比[6]大就放[6]后边,9比[6]大,放到[6]后边,//6出列后大喝一声,比我小的站前边,比我大的站后边,行动吧!霸气十足~

    一趟排完后变成下边这样:

    排序前 6 2 4 1 5 9

    排序后 2 4 1 5 6 9

    b),对前半拉[2 4 1 5]继续进行快速排序

    重复步骤a)后变成下边这样:

    排序前 2 4 1 5

    排序后 1 2 4 5

    前半拉排序完成,总的排序也完成:

    排序前:[6 2 4 1 5 9]

    排序后:[1 2 4 5 6 9]

    排序结束

    以下代码实现仅供参考

    static int partition(int[] unsorted, int low, int high)
            {
                int pivot = unsorted[low];
                while (low < high)
                {
                    while (low < high && unsorted[high] > pivot) high--;
                    unsorted[low] = unsorted[high];
                    while (low < high && unsorted[low] <= pivot) low++;
                    unsorted[high] = unsorted[low];
                }
                unsorted[low] = pivot;
                return low;
            }
    
            static void quick_sort(int[] unsorted, int low, int high)
            {
                int loc = 0;
                if (low < high)
                {
                    loc = partition(unsorted, low, high);
                    quick_sort(unsorted, low, loc - 1);
                    quick_sort(unsorted, loc + 1, high);
                }
            }
    
            static void Main(string[] args)
            {
                int[] x = { 6, 2, 4, 1, 5, 9 };
                quick_sort(x, 0, x.Length - 1);
                foreach (var item in x)
                {
                    Console.WriteLine(item + ",");
                }
                Console.ReadLine();
            }
  • 相关阅读:
    quartz 中JobExecutionContext的使用
    Memcached 集群架构方面的问题
    Spring+Quartz 集群
    Spring Quartz 持久化解决方案
    不同版本(2.3,2.4,2.5) web.xml 的web-app头信息
    Spring Framework 4.0.0发布,首次支持Java 8
    Serializable java序列化
    Quartz 有状态的JobDataMap
    JobDataMap 不能被序列化如何解决研究中
    Spring-3.2.5 + Quartz-2.2.1 集群实例(Tomcat+Memcached+Quartz集群session共享)
  • 原文地址:https://www.cnblogs.com/tinaluo/p/7084486.html
Copyright © 2011-2022 走看看