Algorithm Learning (ii): O (n^2) sorting algorithm

Source: Internet
Author: User

Summarize the learning complexity of O (n^2) for three sorting algorithms: Select Sort, insert sort, hill sort.

(1) Select sort : From the first position start each time find the rest of the position of the smallest value into the current position;

(2) Insert sort : Starting from the second position, each time the value of the current position is inserted in the appropriate position, the insertion sort can bring more efficiency to the almost ordered sequence.

(3) Hill sort : Insert sort with variable step interval, specify a step decay rate, each wheel insert sort completes the numeric sorting of the interval specified step, and when the step decay is 1 o'clock, it becomes the standard insertion sort.

Code implementation:

(1) Select sort

var function (Arr,len) {    var  i,j,min;      for (i = 0; i < len; + +i)        {= i        ;  for (j = i + 1; j < Len; + +j)            {if(Arr[min] > arr[j])                {= j;            }        }        Swap (arr,i,min);}    };

(2) Insert sort

var function (Arr,len) {    var  i,j,k;      for (i = 1; i < Len; + +i)        {= i        ;  for (j = i-1; J >= 0;---J)            {if(Arr[j] > arr[k]) {                swap (arr,k,j);                K--;            } Else {                break;}}}    ;

(3) Hill sort

var function (arr,len,stepinterval) {    var  step,i,j,k;      for (step = Math.floor (len/stepinterval); step > 0; step = Math.floor (Step/stepinterval)) {for        (i = step; i < Len; + +i)            {= i            ;  for (j = i-step; J >= 0 && Arr[j] > Arr[k]; J -= Step) {                swap (arr,k,j)                 ; = J;            }     }}

Summarize:

(1) can be organized from different ways to help understand the playing cards, the choice of sorting is every time from the rest of the cards to take the smallest card to put the last position in the hand;

(2) The key to Hill sort is to understand that it is the insertion sort of step decay.

Algorithm Learning (ii): O (n^2) sorting algorithm

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.