Sorting an Array

Rethna Ganesh
CloudBoost
Published in
3 min readSep 8, 2017

--

Bubble Sort is a vintage solution for sorting an Array. In academic and interviewers circle, it is an important problem, as it gives an opportunity to use nested loops, conditional statements, and shuffling variables. Nice exercise for a thinking developer. Get to know more about bubble sort by googling as there are many good tutorials on the topic. I am not going to explain any further here as it is not used in developing real applications due to atleast the below two reasons.

1. Bubble sort has bad performance
2. It mutates the original array. It means once we sorted the array, the original one is lost.

For beginners who have learned some javascript, a question on Array sorting may look very simple. They learned about array and they know it has a sort method. So their answer is usually

let sortedArr = arr.sort();

They can even ensure that it works correctly by using an array of single digit numbers.

console.log([6, 5, 2, 9, 4].sort());
// output: [2, 4, 5, 6, 9]

But this approach works only for single digit numbers and fail for numbers with 2 or more digits.

For example, for the below array it will not give the correct answer:

console.log([6, 5, 22, 9, 43].sort());
// output: [24, 44, 5, 6, 9]

Let us look into the output carefully and try to predict the behavior. We can understand, the numbers are sorted like a ‘string’ sort. It means first character gets more priority than the second character and so on.

So our understanding is, this may work correctly for sorting an array of strings in alphabetical order.

console.log(['Ram', 'John', 'James'].sort());
// output: ['James', 'John', 'Ram']

But again this will not work correctly if we have mixed case letters. Lets make the first letter in lower case.

console.log(['Ram', 'John', 'james'].sort());
// output: ['John', 'Ram', 'james']

Here, what we expected at the beginning came at the end. Because technically lower case ‘a’ is greater than upper case ‘Z’.

So the bottomline is, we cannot use array.sort() method safely, for any practical situation.

Comparator

The sort method takes an optional argument which should be a function. And this function is know as compactor function.

The compactor function takes two arguments upon which we write the rule : on what basis we compare the array in order to sort it.

So, the below code can be used to sort any array of numbers.

console.log([43,66,44,22,77].sort((a,b) => a-b));

The compactor function returns negative value if their positions has to be interchanged. The above code will be difficult to read if one is not familiar with arrow function. The code should be read as:

console.log([43,66,44,22,77].sort(function(a,b){
return (a-b);
});

In case if we want to sort it in the reverse order. then we should slightly modify our code as below:

console.log([43,66,44,22,77].sort((a,b) => b-a));

To sort an array of string with case insensitivity:

console.log(['Ram', 'John', 'james'].sort(
(a,b) => a.toLowerCase() > b.toLowerCase()));

Array of numbers or strings are less common in real time applications. What we deal with in most of the cases is — an array of objects.

Take for example, a shopping cart application, where we deal with an array of object and each object explains a product like below:

{
name: 'Super Mobile',
price: '100',
reviewsCount: 200,
available: true,
....
}

This is a very typical use case. We will display these array of objects in a grid format, and we may need to sort them based on price or reviewsCount or name, which can be dynamically defined by the user.

To sort the objects based on price, we use the below approach.

function sortByPrice(arr){
return arr.sort((a,b) ==> a.price - b.price);
}

There are many techniques and use cases with respect to sorting array and we have covered only a few of them. Another important point to note is, while sorting, the original array is not modified. Instead a new sorted array is created.

Shuffle an Array

Sorting is a way of ordering an array in a particular fashion. The diagonally opposite operation is shuffling an array in a random way, and we can still use the sort function for doing that.

console.log([1,2,3,4,5].sort(() => (Math.random() — 0.5)))

Here the compactor function doesn’t take any argument as we are not using them. The function simply returns a positive or negative number in a random way.

Conclusion:

The purpose of this blog is NOT to provide a list of cookbook solutions for all possible problems in sorting an array, but just to scratch the surface and ask some intuitive questions and make the developer or learner to think on the topic.

--

--