Author: Hayden Smith 2021
Why?
What?
A few of the popular basic sorting algorithms are:
These sorting algorithms all have an O(n^2) worst-case time complexity. Later we will discuss faster ones.
Moves through the list pair-wise, swapping pairs in the wrong order. Repeats this process until list is sorted.
void bubbleSort(int a[], int lo, int hi) {
int i, j, nswaps;
for (i = lo; i < hi; i++) {
nswaps = 0;
for (j = hi; j > i; j--) {
if (less(a[j], a[j-1])) {
swap(a[j], a[j-1]);
nswaps++;
}
}
if (nswaps == 0) break;
}
}Find the smallest element, swap it with first array slot.
Find the second smallest element, swap it with second array slot.
Etc, until traversed through entire array.
Source: https://algorithms.tutorialhorizon.com/selection-sort-java-implementation/
void selectionSort(int a[], int lo, int hi) {
int i, j, min;
for (i = lo; i < hi-1; i++) {
min = i;
for (j = i+1; j <= hi; j++) {
if (less(a[j],a[min])) min = j;
}
swap(a[i], a[min]);
}
}Take first element and treat as sorted array; take next element and insert into sorted part of array so that order is preserved; repeat until whole array is sorted
void insertionSort(int a[], int lo, int hi) {
int i, j, val;
for (i = lo+1; i <= hi; i++) {
val = a[i];
for (j = i; j > lo; j--) {
if (!less(val,a[j-1])) break;
a[j] = a[j-1];
}
a[j] = val;
}
}Most sorts assume we work on arrays. However, we can still sort on linked lists.