Algorithms: Common sorting algorithms

Source: Internet
Author: User

Recently collated the commonly used sorting algorithm, tidy up, leave their own thinking process.

1. Bubble Sort:

(1) Average time complexity: O (n2)

(2) Best time complexity: O (N)

(3) Worst time complexity: O (n2)

(5) Space complexity: O (1)

(5) Stability: stable

(6) JavaScript implementations:

functionBubble (arr) {varLen =arr.length; vartmp; //the outer loop is responsible for controlling the number of times to sort     for(vari = 0; i < len-1; i++){       //the inner loop is responsible for making a trip to sort        for(varj = 0; J < len-1-I; J + +){          if(Arr[j + 1] <Arr[j]) {tmp=Arr[j]; ARR[J]= Arr[j + 1]; Arr[j+ 1] =tmp;       };    };    }; returnarr;};

2. Select Sort:

(1) Average time complexity: O (n2)

(2) Best time complexity: O (n2)

(3) Worst time complexity: O (n2)

(4) Space complexity: O (1)

(5) Stability: unstable

(6) JavaScript implementations:

functionSelect (arr) {varLen =arr.length; //the outer loop requires len-1 sequencing    for(vari = 0; i < len-1; i++){      varindex =i; varMin =Arr[i]; vartmp; //The inner Loop compares the smallest one in an array element that is never sorted       for(varj = i + 1; J < Len; J + +){         if(Min >Arr[j]) {Index=J; Min=Arr[j];      };      }; //put it at the end of the sorted array elementTMP =Arr[i]; Arr[i]=min; Arr[index]=tmp; };};

3. Insert Sort:

(1) Average time complexity: O (n2)

(2) Best time complexity: O (N)

(3) Average time complexity: O (n2)

(4) Space complexity: O (1)

(5) Stability: stable

(6) JavaScript implementations:

functionInsert (arr) {varLen =arr.length; vartmp;  for(vari = 1; i < Len; i++){      //Take out the current array elementTMP =Arr[i];  for(varj = i-1; J >= 0; j--){         if(Arr[j] >tmp) {Arr[j+1] =Arr[j];      }      }; //inserting the extracted array elementsARR[J+1] =tmp;   }; returnarr;}

Algorithms: Common sorting algorithms

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.