內排序-快速排序

來源:互聯網
上載者:User

標籤:lin   有序   quick   目的   class   交換   部分   str   獲得   

演算法思想:通過一趟排序將待排序列分割成獨立的兩部分,其中一部分均比另外一部分小,則可對這兩部分繼續繼續排序,重複之前步驟,以達到整個序列有序的目的.它是由圖靈獲得者 Tony Hoare設計出來的,該演算法被列為20世紀十大演算法之一.

 

 //尋找關索引值的位置,最後一次性移過去    class QuickSort_1    {        static void Main(string[] args)        {            int[] a = new int[] { 20, 30, 90, 40, 70, 110, 60, 10, 100, 50, 80,9,8,7,6 };                   QuickSort_1 quickSort = new QuickSort_1();            quickSort.Sort(a, 0, a.Length - 1);            foreach (int i in a)            {                Console.WriteLine(i);            }            Console.ReadLine();        }        /// <summary>        /// 交換資料        /// </summary>        /// <param name="datas"></param>        /// <param name="index1"></param>        /// <param name="index2"></param>        void ExchangeData(int[] datas, int index1, int index2)        {            if (index1 < 0 || index2 < 0 || index1 >= datas.Length || index2 >= datas.Length)            {                return;            }                      datas[index1] = datas[index2] + (datas[index2] = datas[index1]) * 0;        }        public void Sort(int[] arrays, int left_index, int right_index)        {            if (left_index == right_index) return;            int important = left_index;//關索引值            int cur_left = left_index;//左遊標            int cur_right = right_index;//右遊標                       while (cur_left < cur_right)//當左右遊標未相遇時            {                while (arrays[cur_right] >= arrays[important] && cur_left < cur_right)                {                    cur_right--;//先從右遊標開始 ,遞減遇到小於關鍵元素的值                }                while (arrays[cur_left] <= arrays[important] && cur_left < cur_right)                {                    cur_left++;//再從左遊標開始 ,遞減遇到大於關鍵元素的值                }                if (cur_left <cur_right && arrays[cur_left] > arrays[cur_right])                {                    ExchangeData(arrays, cur_left, cur_right);//當遊標未相遇時,並且前值大於後值時,交換這兩個遊標指向的值                }            }            if (cur_left == cur_right )            {//當遊標相遇時                ExchangeData(arrays, important, cur_right);//把關索引值交換到相遇位置                important = cur_left;                Sort(arrays, left_index, important - 1);// 將關索引值左邊的序列 重複以上過程                Sort(arrays, important + 1, right_index);//將關索引值右邊的序列 重複以上過程            }        }    }

 

內排序-快速排序

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.