|
| 1 | +// Sorting algorithms |
| 2 | + |
| 3 | +// Bubble sort approach: |
| 4 | +// Time complexity: Best case (items are already sorted): O(n), Average case: O(n^2) ,Worst case (all items sorted in opposite order): O(n^2) |
| 5 | +// Space complexity: O(1) |
| 6 | +export const bubbleSort = ([...items]) => { |
| 7 | + for (let a = 0; a < items.length - 1; a++) { |
| 8 | + for (let b = a + 1; b < items.length; b++) { |
| 9 | + if (items[a] > items[b]) { |
| 10 | + const newA = items[b]; |
| 11 | + items[b] = items[a]; |
| 12 | + items[a] = newA; |
| 13 | + } |
| 14 | + } |
| 15 | + } |
| 16 | + return items; |
| 17 | +}; |
| 18 | + |
| 19 | +// Quicksort approach: |
| 20 | +// Time complexity: Best case (random order): O(n * log n), Worst case (items are already sorted): O(n^2) |
| 21 | +// Space complexity: O(n) - recursive calls |
| 22 | +export const quickSort = (items) => { |
| 23 | + const copiedArr = items; |
| 24 | + if (copiedArr.length <= 1) { |
| 25 | + return copiedArr; |
| 26 | + } |
| 27 | + const smallerArr = []; |
| 28 | + const largerArray = []; |
| 29 | + const pivotEl = copiedArr.shift(); |
| 30 | + const equalArray = [pivotEl]; |
| 31 | + |
| 32 | + while (copiedArr.length) { |
| 33 | + const currentEl = copiedArr.shift(); |
| 34 | + currentEl === pivotEl && equalArray.push(currentEl); |
| 35 | + currentEl > pivotEl && largerArray.push(currentEl); |
| 36 | + currentEl < pivotEl && smallerArr.push(currentEl); |
| 37 | + } |
| 38 | + |
| 39 | + const smallerElSorted = quickSort(smallerArr); |
| 40 | + const largerElSorted = quickSort(largerArray); |
| 41 | + return smallerElSorted.concat(equalArray, largerElSorted); |
| 42 | +}; |
| 43 | + |
| 44 | +// Merge sort approach: |
| 45 | +// Time complexity: O(n * log n) |
| 46 | +// Space complexity: O(n) - recursive calls |
| 47 | +export const mergeSort = (arr) => { |
| 48 | + if (arr.length < 2) return arr; |
| 49 | + if (arr.length === 2) return arr[0] > arr[1] ? [arr[1], arr[0]] : arr; |
| 50 | + const middleIndex = Math.floor(arr.length / 2); |
| 51 | + |
| 52 | + const leftArr = arr.slice(0, middleIndex); |
| 53 | + const rightArr = arr.slice(middleIndex); |
| 54 | + |
| 55 | + const leftSortedArr = mergeSort(leftArr); |
| 56 | + const rightSortedArr = mergeSort(rightArr); |
| 57 | + |
| 58 | + const mergedArr = []; |
| 59 | + let leftArrIndex = 0; |
| 60 | + let rightArrIndex = 0; |
| 61 | + while ( |
| 62 | + leftArrIndex < leftSortedArr.length || |
| 63 | + rightArrIndex < rightSortedArr.length |
| 64 | + ) { |
| 65 | + if ( |
| 66 | + leftArrIndex >= leftSortedArr.length || |
| 67 | + leftSortedArr[leftArrIndex] > rightSortedArr[rightArrIndex] |
| 68 | + ) { |
| 69 | + mergedArr.push(rightSortedArr[rightArrIndex]); |
| 70 | + rightArrIndex++; |
| 71 | + } else { |
| 72 | + mergedArr.push(leftSortedArr[leftArrIndex]); |
| 73 | + leftArrIndex++; |
| 74 | + } |
| 75 | + } |
| 76 | + return mergedArr; |
| 77 | +}; |
0 commit comments