Sorting Algorithms

Sorting an array with an higher order function now a days is very easy.

let x = [2,5,8,1,3]
x.sort() //[1,2,3,5,8]

Now doing same thing with vanilla JavaScript algorithms.

let a = [5,2,1,3,7,100];
let Alen = a.length;
let ans = [];
for(let i=0; i<Alen; i++) {
    let index = 0;
     let minValue = a[0];
     for(let j=1; j<a.length; j++){
         if(a[j] < minValue) {
              minValue = a[j];
              index = j;
         }
     }
     ans.push(minValue);
     a.splice(index, 1);
}

console.log(ans);  // [1, 2, 3, 5, 7, 100]

Bubble sort Algorithm

function bubbleSort(arrayItem) {
    let n = arrayItem.length;
    for(let i=0; i<n-1; i++) {
        let minTillNow = arrayItem[i];
         for(let j=i+1; j<n; j++) {
           if(arrayItem[j] < minTillNow) {
              minTillNow = arrayItem[j];
              let temp = arrayItem[i];
              arrayItem[i] = arrayItem[j];
              arrayItem[j] = temp;
            }
         }
    }
    return arrayItem;
}

let a = bubbleSort([2,1,3,85,8])

Leave a Reply

Your email address will not be published. Required fields are marked *