Sorting algorithms with Javascript

Sorting algorithms with Javascript

The basics of Data Structure.

The sorting algorithms are the fundamentals of Data structure and are considered important if one wants to develop logical thinking. So here, we'll be looking at the 4 most popular sorting algorithms and implement them using Javascript.
So let's get right into it.

The algorithms that we'll be implementing, are :

  • Bubble Sort
  • Selection Sort
  • Insertion Sort
  • Merge Sort

Bubble Sort

As the name suggests, the elements in the collection are sorted one by one as a bubble moves upward from the bottom of a water body to the surface.
In bubble sort, there are 'n' number of passes, where n is the number of elements and in each pass, the largest element is shifted to the end of the collection.
The code:

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

Selection Sort

In selection sort, we select the smallest element after the ith element in each ith pass and then replace it with the ith element.(Where i ranges from 0 to ArrayLength-1)
Therefore, there are n no. of passes and in each ith pass, the array is sorted from array[0] to array[i].
The code:

function selectionSort(arr){
    for(let i=0;i<arr.length;i++){
        let min=i;
        for(let j=i+1;j<arr.length;j++){
            if(arr[j]<arr[min]){
                min=j;
            }
        }
        if(min!=i){
            [arr[min],arr[i]]=[arr[i],arr[min]];
        }
    }
    return arr;
}

Insertion Sort

Starting from the second element, in every ith pass, we check whether the ith element is smaller than any element behind it, if it is, then it's swapped with that element. Hence, after every ith pass, the array is sorted from 0 to the ith element.(i ranges from 0 to arrayLength -1).
The code:

function insertionSort(arr){
    for(let i=1;i<arr.length;i++){
        let j=i;
        while(j>0 && arr[j]<arr[j-1]){
            let temp=arr[j];
            arr[j]=arr[j-1];
            arr[j-1]=temp;
            j--;
        }
    }
    return arr;
}

Merge Sort

The merge sort keeps on dividing the array into two halves until the arrays are down to just 1 element inside them. Then it merges the singleton arrays in a sorted way and keeps on merging until the original array is obtained. Hence, finally, it returns a sorted array.
The code:

function merge(left, right){
  var result = [],
      lLen = left.length,
      rLen = right.length,
      l = 0,
      r = 0;
  while(l < lLen && r < rLen){
     if(left[l] < right[r]){
       result.push(left[l++]);
     }
     else{
       result.push(right[r++]);
    }
  }  
  //remaining part needs to be addred to the result
  return result.concat(left.slice(l)).concat(right.slice(r));
}

function mergeSort(arr){
   var len = arr.length;
   if(len <2)
      return arr;
   var mid = Math.floor(len/2),
       left = arr.slice(0,mid),
       right =arr.slice(mid);
   //send left and right to the mergeSort to broke it down into pieces
   //then merge those
   return merge(mergeSort(left),mergeSort(right));
}

There are a lot more sorting algorithms, but if you are starting from scratch in any language, I feel like these algorithms should give you the basic idea of the building blocks of a language, that is:

  • variable declarations
  • Conditionals
  • Loops
  • Functions


Thanks for reading my first ever blog😊.