經典排序演算法 – 快速排序Quick sort

來源:互聯網
上載者:User

經典排序演算法 - 快速排序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();        }

返回主目錄 [經典排序演算法][集錦]

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.