Sort
Bubble Sort
Sorting from Smallest to Largest
function bubbleSort(array) {
let n = array.length;
let swapped;
do {
swapped = false;
for (let i = 1; i < n; i++) {
if (array[i - 1] > array[i]) {
[array[i - 1], array[i]] = [array[i], array[i - 1]]; // if the current element is smaller than the previous one, swap them
swapped = true; // mark that a swap was performed
}
}
n--; // decrease n, because the last element is now in its correct position
} while (swapped); // repeat the process as long as swaps are being made
return array; // return the sorted array
}
Sorting from Largest to Smallest
function bubbleSortDescending(array) {
let n = array.length;
let swapped;
do {
swapped = false;
for (let i = 1; i < n; i++) {
if (array[i - 1] < array[i]) {
[array[i - 1], array[i]] = [array[i], array[i - 1]]; // if the current element is larger than the previous one, swap them
swapped = true; // mark that a swap was performed
}
}
n--; // decrease n, because the last element is now in its correct position
} while (swapped); // repeat the process as long as swaps are being made
return array; // return the sorted array
}
Merge Sort
function mergeSort(array) {
if (array.length <= 1) {
return array;
}
const middle = Math.floor(array.length / 2);
const left = array.slice(0, middle);
const right = array.slice(middle);
return merge(mergeSort(left), mergeSort(right));
}
function merge(left, right) {
let result = [];
let leftIndex = 0;
let rightIndex = 0;
while (leftIndex < left.length && rightIndex < right.length) {
if (left[leftIndex] <= right[rightIndex]) {
result.push(left[leftIndex]);
leftIndex++;
} else {
result.push(right[rightIndex]);
rightIndex++;
}
}
return result.concat(left.slice(leftIndex)).concat(right.slice(rightIndex));
}
const array = [34, 7, 23, 32, 5, 62];
const sortedArray = mergeSort(array);
console.log(sortedArray); // Output will be [5, 7, 23, 32, 34, 62]