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
Yes, it does!
...but it doesn't always work the way you expect.
[ "Steele", "Colt", "Data Structures", "Algorithms" ].sort();
// [ "Algorithms", "Colt", "Data Structures", "Steele" ]
[ 6, 4, 15, 10 ].sort();
// [ 10, 15, 4, 6 ]
Examples
function numberCompare(num1, num2) {
return num1 - num2;
}
[ 6, 4, 15, 10 ].sort(numberCompare);
// [ 4, 6, 10, 15 ]
function compareByLen(str1, str2) {
return str1.length - str2.length;
}
[ "Steele", "Colt", "Data Structures", "Algorithms" ]
.sort(compareByLen);
// [ "Colt", "Steele", "Algorithms", "Data Structures" ]
// ES5
function swap(arr, idx1, idx2) {
var temp = arr[idx1];
arr[idx1] = arr[idx2];
arr[idx2] = temp;
}
// ES2015
const swap = (arr, idx1, idx2) => {
[arr[idx1],arr[idx2]] = [arr[idx2],arr[idx1]];
}
Many sorting algorithms involve some type of swapping functionality (e.g. swapping to numbers to put them in order)
A sorting algorithm where the largest values bubble up to the top!
[ 5, 3, 4, 1, 2 ]
[ 3, 5, 4, 1, 2 ]
[ 3, 4, 5, 1, 2 ]
[ 3, 4, 1, 5, 2 ]
[ 3, 4, 1, 2, 5 ]
5 is now in its sorted position!
Similar to bubble sort, but instead of first placing large values into sorted position, it places small values into sorted position
[ 5, 3, 4, 1, 2 ]
[ 5, 3, 4, 1, 2 ]
[ 5, 3, 4, 1, 2 ]
[ 5, 3, 4, 1, 2 ]
[ 1, 3, 4, 5, 2 ]
1 is now in its sorted position!
Builds up the sort by gradually creating a larger left half which is always sorted
[ 5, 3, 4, 1, 2 ]
[ 3, 5, 4, 1, 2 ]
[ 3, 4, 5, 1, 2 ]
[ 1, 3, 4, 5, 2 ]
[ 1, 2, 3, 4, 5 ]
Algorithm | Time Complexity (Best) | Time Complexity (Average) | Time Complexity (Worst) | Space Complexity |
---|---|---|---|---|
Bubble Sort | O(n) | O(n ) | O(n ) | O(1) |
Insertion Sort | O(n) | O(n ) | O(n ) | O(1) |
Selection Sort | O(n ) | O(n ) | O(n ) | O(1) |
2
2
2
2
2
2
2