DEV Community

Cover image for Iterative Sorting algorithms in Javascript

Iterative Sorting algorithms in Javascript

Arkar Kaung Myat on May 23, 2023

Sorting algorithms are important in computer science because they help us organize data so it's easier to work with. I'll discuss three sorting alg...
Collapse
 
kalkwst profile image
Kostas Kalafatis

Hey there! While your implementations are correct, there is still room for optimization. Let me share my thoughts with you.

Insertion Sort

  • Move the the variable declaration of current outside the inner loop. This avoids reassigning it in each iteration of the inner loop.
  • Adjust the condition in the inner loop to j>=0 for better readability
  • Remove the unnecessary j-- inside the inner loop.
function insertionSort(arr) {
  var length = arr.length;

  for (var i = 1; i < length; i++) {
    var current = arr[i];
    var j = i - 1;

    while (j >= 0 && arr[j] > current) {
      arr[j + 1] = arr[j];
      j--;
    }

    arr[j + 1] = current;
  }

  return arr;
}
Enter fullscreen mode Exit fullscreen mode

Bubble Sort

  • Move the swapped variable declaration outside the outer loop to reset it for each iteration. This will avoid unnecessary iterations when the array is already sorted.
  • Change the condition in the outer loop to i < length - 1 to avoid unnecessary iterations. After each pass, the largest element gets placed at the end, so the last i elements are already sorted.
  • Use array destructuring to swap elements in the inner loop, eliminating the need for a temporary variable.
function bubbleSort(arr) {
  var length = arr.length;
  var swapped;

  for (var i = 0; i < length - 1; i++) {
    swapped = false;

    for (var j = 0; j < length - 1 - i; j++) {
      if (arr[j] > arr[j + 1]) {
        var tmp = arr[j + 1];
        arr[j + 1] = arr[j];
        arr[j] = tmp;
        swapped = true;
      }
    }

    if (!swapped) {
      break; // If no swap occurred in the inner loop, the array is already sorted
    }
  }

  return arr;
}
Enter fullscreen mode Exit fullscreen mode

Also, your implementations are written in Typescript not Javascript.

Keep up the good work!