Implementing Custom Sorting Algorithm in JavaScript

💡 A small algorithmic discovery while revisiting sorting algorithms While revisiting sorting concepts like Bubble Sort and Insertion Sort, I tried implementing my own approach to sort an array. Interestingly, the logic that came to my mind turned out to be very similar to the idea behind Insertion Sort. The approach was simple: • Start from the second element of the array • Compare the current element with previous elements • Shift larger elements to the right • Insert the current element in its correct position Here is the JavaScript snippet I came up with: const getSortedArr = (arr) => { const n = arr.length; for (let i = 1; i < n; i++) { let curr = arr[i]; let prev = i - 1; while (arr[prev] > curr && prev >= 0) { arr[prev + 1] = arr[prev]; arr[prev] = curr; prev--; } } return arr; }; 📊 Complexity Analysis • Time Complexity - Best Case: O(n) - Average Case: O(n²) - Worst Case: O(n²) • Space Complexity - O(1) (in-place sorting) #JavaScript #Algorithms #Sorting #Learning #SoftwareEngineering #ProblemSolving

To view or add a comment, sign in

Explore content categories