Address
Whiteland, IN 46184
Work Hours
Monday to Friday: 9AM - 5PM
Weekend: 1PM - 3PM
What is Sorting?
Sorting is the process of rearranging the items in a collection (e.g. an array) so that the items are in some kind of order.
Examples
Why do we need to Learn this
JavaScript has built-in sort methods but they don’t always work as expected
The sort above worked well,
The sort below not so well
Telling Javascript how to sort
Telling Javascript how to sort(Examples)
Let us talk about two different simple Sorting algorithms
Bubble Sort
A sorting algorithm where the largest values bubble up to the top!. We start from the first element and check is the first element greater than the next element, if yes, switch. We keep doing this till we get it to its rightful spot in the array, then we start again.
Take the array for example
Actual Code
Selection Sort
Similar to bubble sort, but instead of first placing large values into a sorted position, it places small values into a sorted position.
Take the array below.
Pseudocode
Actual Code
Time Complexities of the two sorting algorithms
Algorithm | Time Complexity (Best) | Time Complexity (Average) | Time Complexity (Worst) | Space Complexity |
Bubble Sort | O(n) | O(n ) | O(n ) | O(1) |
Selection Sort | O(n ) | O(n ) | O(n ) | O(1) |
In the next article, we shall look at another basic sorting algorithm and some intermediate ones. Till next time 🙂