# JS -- simple sorting of sorting algorithm

Keywords: Javascript less

Catalog

# Simple sorting of JS sorting

## Bubble sort

• Time complexity: O(n^2)
• Stable sorting algorithm
• Features: looking from the back to the front, all the numbers in the ordered area must be less than (or greater than) the numbers in the disordered area
• Performance: slow
• Optimization: two way bubbling (cocktail sorting)
```    function bubbleSort(ary) {
let exchange = 0,
temp = null,
n = ary.length;
// I < n-1 instead of I < n, when traversing to n-1 times, it is nearly in order,
for(let i=0; i<n-1; i++) {
// Traverse from the back to the front, comparing the previous term with the latter
for(let j = n-2; j>=i; j--) {
if(ary[j+1] < ary[j]) {
temp = ary[j];
ary[j] = ary[j+1];
ary[j+1] = temp;
exchange = 1;
}
}
// If no exchange occurs (indicating that the sorting is completed), exit the sorting directly
if(exchange) break;
}
return ary;
}```

Effect example:

## Direct insert sort

• Time complexity: O(n^2)
• Stable sorting algorithm
• Features: single front element is inserted into the front ordered area for sorting, and the elements in the ordered area are not necessarily less than (greater than) the elements in the disordered area
• Performance: fast when array elements are basically ordered
• Optimization: set the increment, make the array basically orderly, and then continuously reduce and enhance (Hill sort)
```    function straightInsertionSort(ary) {
let n = ary.length,
temp = null;
for (let i = 1; i < n; i++) {
// If the latter item is smaller than the former, it indicates that the exchange is needed
if (ary[i] < ary[i - 1]) {
// temp = item to be exchanged
temp = ary[i];
let j = i - 1;
do {
// Front move back
ary[j + 1] = ary[j];
j--;
} while (j >= 0 && temp < ary[j]); // Find where temp needs to be inserted
// Insert temp
ary[j + 1] = temp;
}
}
return ary;
}```

Effect display:

## Direct selection sorting

• Time complexity: O(n^2)
• Unstable sorting algorithm
• Features: find the smallest (largest) from the front to the back, and then exchange with the first. The ordered area must be smaller (larger) than the unordered area
• Performance: better than bubbling
• Cause of instability: the exchange of elements may directly span multiple elements, and the position of equivalent elements may change
• For example: 553 = > when sorting, the first 5 and 3 are directly exchanged. The first 5 goes after the second 5, and the position changes
```  function straightSelectSort(ary) {
let n = ary.length,
temp = null;
for(let i=0; i<n-1; i++) {
let k = i;
for(let j = i+1; j<n; j++) {
// Where to find the minimum
if(ary[j]<ary[k]) k=j;
}
if(k!== i) {
temp = ary[i];
ary[i] = ary[k];
ary[k] = temp;
}
}
return ary;
}```

Effect example:

gif source: Sorting algorithm - scatter visualization

Posted by freedomclan on Fri, 20 Mar 2020 10:44:40 -0700