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