Bubble sort
Can take one array of unsorted values. Has one loop with a nested loop inside. it checks elements of the array two by two and swaps them if the first value is bigger than the second. One important thing is that the nested loop is likefor(let j = 0; j < array.length - i; j++) { which as i increases, it will ignore the last element/s in the array.
2,5,1,7,3
2,5,1,3,7
2,1,3,5,7
1,2,3,5,7
Merge sort
The main function splits an array into two arrays and keeps splitting until there is only one number is left in the array then it will compare arrays two by two and sort values.
function merge(array) {
if(array.length <= 1) return array;
const middle = Math.floor(array.length / 2);
const left = merge(array.slice(0, middle));
console.log(left)
const right = merge(array.slice(middle));
return merger(left, right)
}
Insertion sort
1* Start by picking the second element in the array
2* Now compare the second element with the one before it and swap if necessary.
3* Continue to the next element and if it is in the incorrect order, iterate through the sorted portion (i.e. the left side) to place the element in the correct place.
4.Repeat until the array is sorted.
[ 5, 3, 4, 1, 2 ]
[ 3, 5, 4, 1, 2 ]
[ 3, 4, 5, 1, 2 ]
[ 1, 3, 4, 5, 2 ]
[ 1, 2, 3, 4, 5 ]
function insertionSort(arr) {
for(let i = 1; i < arr.length; i++) {
let currentEl = arr[i]
let j = i - 1;
while(j >= 0 && arr[j] > currentEl) {
arr[j + 1] = arr[j]
console.log(j)
console.log(i)
j--
}
arr[j + 1] = currentEl; }return arr;
}
Selection sort
function selectionSort(arr) {
for(let i = 0; i < arr.length - 1; i++) {
let minIndex = i;
// Find the index of the minimum element in the unsorted part of the array
for(let j = i + 1; j < arr.length; j++){
if(arr[j] < arr[minIndex]) {
minIndex = j
}
}
// Swap the found minimum element with the first element
if(minIndex !== i) {
let temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
} }return arr;
}
Radix sort
Pivot algorithm