The original: A daily walkthrough of the classic Algorithm--the 24th comb sort
This article again look at a classic sorting, comb sorting, why the name of comb, maybe each comb has its own gap bar, large comb gap larger, small comb gap smaller.
In the previous article, we saw that the cocktail sort was optimized in the bubble sort, and the one-way comparison turned into two-way, and the comb sort here also made some optimizations on the bubbling sort.
Bubble sort on our selection is adjacent to the two number to do the comparison, that is their gap of 1, in fact, comb sort put forward a different point of view, if the gap here is set to a certain size,
Efficiency must be gap=1 more efficient.
Below we look at the specific idea, comb sort has such a 1.3 ratio value, each trip compares, will use this 1.3 to decrement the gap, until gap=1 when becomes the bubble sort, this
The algorithm is more efficient than the bubble sort, the time complexity O (n2/2p) Here is the increment of P, is not a bit like hill sort of likeness ...
For example, there is a set of data: the initialization of the gap=list.count/1.3, and then use the gap as an array subscript for cross-numeric comparison size, the former is greater than the latter to exchange,
Each trip is sorted and divided by 1.3, and finally removed to Gap=1
Finally, our array is sorted out, here's the code:
1 usingSystem;2 usingSystem.Collections.Generic;3 usingSystem.Linq;4 usingSystem.Text;5 usingSYSTEM.XML.XSL;6 7 namespaceConsoleApplication18 {9 class ProgramTen { One Static voidMain (string[] args) A { -list<int> list =Newlist<int> () {8,1,4,2,9,5,3 }; - theConsole.WriteLine ("\ n Sort before = = {0}\n",string. Join (",", list)); - -List =Combsort (list); - +Console.WriteLine ("\ n Sort after = {0}\n",string. Join (",", list)); - + Console.read (); A } at - /// <summary> - ///Comb Sort - /// </summary> - /// <param name= "list" ></param> - /// <returns></returns> in Staticlist<int> Combsort (list<int>list) - { to //get the best sort size: ratios of 1.3 + varStep = (int) Math.floor (list. Count/1.3); - the while(Step >=1) * { $ for(inti =0; I < list. Count; i++)Panax Notoginseng { - //if the former is greater than the latter, the Exchange the if(i + Step < list.) Count && List[i] > list[i +Step]) + { A vartemp =List[i]; the +List[i] = list[i +step]; - $List[i + Step] =temp; $ } - - //if it crosses the border, jump directly out the if(i + Step >list. Count) - Break;Wuyi } the - //In the current step in addition to the 1.3 WuStep = (int) Math.floor (Step/1.3); - } About $ returnlist; - } - } -}
The daily walkthrough of the classic Algorithm question--the 24th comb sort