This tutorial is about two fundamental, and basic, sorting algorithms. If you are new to sorting, I'd recommend you come up with your own algorithm for sorting arrays first, and then compare it with these algorithms. These fundamental sorting techniques give you important insights into:
- How to sort arrays
- How you can improve an algorithm, and
- Under what conditions you should apply a certain sort procedure
xxxxxxxxxx
46
printArray(myArr2);
function swap(X, ind1, ind2) {
let temp = X[ind1];
X[ind1] = X[ind2];
X[ind2] = temp;
}
​
function bubbleSort(X) {
let n = X.length;
let sorted = false;
let totalSorted = 0;
while (totalSorted < (n-1) && !sorted) {
sorted = true;
for(let i = 1; i <= n-1-totalSorted; ++i) {
if (X[i-1] > X[i]) {
swap(X, i-1, i);
sorted = false;
}
}
totalSorted++;
}
}
​
function insertionSort(X) {
let totalSorted = 1;
let n = X.length;
while (totalSorted <= (n-1)) {
let i = totalSorted;
while(i > 0 && X[i-1] > X[i]) {
swap(X, i-1, i);
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment