We will learn some of the basic and popular sorting algorithms. But before we directly jump on the topic let’s first understand some parameters used to describe/evaluate a sorting algorithm.
The time complexity of an algorithm quantifies the amount of time taken by an algorithm to run as a function of the length of the input.
The space complexity of an algorithm is the amount of memory space required to solve an instance of the computational problem as a function of the length of the input.
Consider you have an array [2, 4, 4] & let’s rename it to [2, 4i, 4j] for understanding purpose. Some sorting algorithms will keep the 4 in its respective positions [2, 4i, 4j] while some sorting algorithms will swap the positions of 4 like [2, 4j, 4i] while sorting.
Algorithms which does not change the positions of equally-weighted numbers from their relative positions in the input are known to be Stable while algorithms which change the respective positions of numbers are known as UnStable
let unsorted = [5,1,8,4,9,6,7,2,3]
swap=(array, leftIndex, rightIndex)=>{
var temp = array[leftIndex];
array[leftIndex] = array[rightIndex];
array[rightIndex] = temp;
}
selectionSort=(array)=>{
console.log(`Iteration 0 :` ,array.join(' '))
for(let i=0; i<array.length; i++){
let min = i
for(let j=i; j<array.length; j++){
if(array[min]> array[j]){
min = j
}
}
swap(array, min, i) // Swap Positions
console.log(`Iteration ${i+1} :` ,array.join(' '))
}
}
selectionSort(unsorted) // Invoking Sort
Time Complexity
------------------------
Best Case : O(n^2)
Average Case : O(n^2)
Worst Case : O(n^2)
------------------------
Space Complexity : O(n)
Stability: Stable
Selection Sort Output
_The sorting happens in the order of the index of an array. It first selects the position of the elements & finds outs the element that belongs to that position & hence called _selection sort
#computer-science #javascript #engineering #sorting-algorithms #interview #programming