Cleaning Up Your Sorting Methods with the Swap Method

Matt Lazewski
2 min readDec 11, 2020

If you have ever had to prepare for a technical interview, odds are is you are familiar with some basic sorting methods. You have probably suffered through coding bubble, insertion, and selection sort methods only to find out later that the time and space complexity of all of them isn’t exactly ideal. Nonetheless, if you plan on landing a top tech job, you need to know them. In this article I’m going to demonstrate adding a swap function to your sorting methods to clean up your code and move some of your functionality.

We are going to use the insertion sort method for this example, but like I previously stated this helper function will work with any other sorting method. If you are unfamiliar with the insertion sort method, basically what we are doing is iterating through an array one element at a time and determining its place based on the values around it. Let’s take a closer look:

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

We start the iteration at index 1 and work backwards. We reassign the value of i and start our work backwards with a while loop that swaps j with the element before it as long it is less than the number in the previous index. Here is an animation to help visual the movement:

With the variable i adding each time through and j subtracting, we are able to ensure we do not go too far in either direction. Now for the real reason we are here, the swap method.

function swap(element1, element2, array){  const temp = array[element2];  array[element2] = array[element1];  array[element1] = temp;};

All we are doing is assigning our second element to a temporary variable, so we don’t lose it. Then we assign the second element the value of the first element and then finally give the first element the value of our temporary element, which is the second element’s value. Just like that we have successfully swapped the two items in an array. We could have just as easily added this functionality to our while loop and it would have sorted just fine, but when we separate our functionality not only does our code look cleaner but if this were a real application we could reuse that swap method in other parts of our code. Let’s take a look at our sorting method all together.

function insertionSort(array){  for(let i = 0; i < array.length; i ++){    let j = i;

while(j > 0 && array[j] < array[j - 1]){
swap(j , j - 1, array); j -= 1; } } return array;}function swap(element1, element2, array){ const temp = array[element2]; array[element2] = array[element1]; array[element1] = temp;};

--

--

Matt Lazewski

Rookie coder trying to find my way into the tech world.