UNPKG

algolibrary

Version:
119 lines (99 loc) 2.76 kB
/** * author: Gowru Sree Vathsa * Created on: 28th Dec 2024 * Last modified on: 28th Dec 2024 */ /** * Bubble Sort implementation. * * This function sorts an array of numbers using the bubble sort algorithm. * * **Time Complexity:** * - Best Case: O(n) (when the array is already sorted) * - Average Case: O(n^2) * - Worst Case: O(n^2) (when the array is sorted in reverse order) * * **Space Complexity:** O(1) (in-place sorting) * * @param {number[]} arr - The array of numbers to be sorted. * @param {number} desc - Flag to determine sorting order. * 0 (default): Ascending order. * Any other value: Descending order. * @returns {number[]} - The sorted array. */ function sort(arr, sortBy){ if(sortBy instanceof Function){ return bubbleSortWithCompare(arr, sortBy); } else if(typeof sortBy === "number"){ return bubbleSort(arr, sortBy); } } function bubbleSort(arr, desc = 0){ // Check if the input is an array. if(!Array.isArray(arr)){ throw new Error("Invalid input. Expected an array."); } // Check if the array is empty. if(arr.length === 0){ return arr; } // Sort based on the provided flag. if(desc == 0){ return bubbleSortAsc(arr); } else{ return bubbleSortDesc(arr); } } function bubbleSortWithCompare(arr, compareFn = (a, b) => a > b){ let len = arr.length; let swapped; do{ swapped = false; for(let i = 0; i<len-1; ++i){ // Compare adjacent elements and swap them if they are in the wrong order. if(compareFn(arr[i], arr[i+1])){ [arr[i], arr[i+1]] = [arr[i+1], arr[i]]; swapped = true; } } --len; } while(swapped); return arr; } function bubbleSortAsc(arr){ let len = arr.length; let swapped; do{ swapped = false; for(let i = 0; i<len-1; ++i){ // Compare adjacent elements and swap them if they are in the wrong order. if(arr[i] > arr[i+1]){ [arr[i], arr[i+1]] = [arr[i+1], arr[i]]; swapped = true; } } --len; } while(swapped); return arr; } function bubbleSortDesc(arr){ let len = arr.length; let swapped; do{ swapped = false; for(let i = 0; i<len-1; ++i){ // Compare adjacent elements and swap them if they are in the wrong order. if(arr[i] < arr[i+1]){ [arr[i], arr[i+1]] = [arr[i+1], arr[i]]; swapped = true; } } --len; } while(swapped); return arr; } module.exports = { sort };