Assumption: All numbers in the array are distinct.
The bad ones (Ο(N2)):
void sort(double A[], int N)
{
for(i = 0; i < N; i++) {
for(j = 0; j < N-1; j++) {
if (A[j] > A[j+1])
swap(A, j, j+1);
}
}
}
void sort(double A[], int N)
{
for(i = 1; i < N; i++) {
temp = A[i];
for(j = i-1; j >= 0 && A[j] > temp; j--) {
A[j+1] = A[j];
}
A[j+1] = temp;
}
}
void sort(double A[], int N)
{
for(i = 0; i < N - 1; i++) {
smallest = i;
for(j = i+1; j < N; j++) {
if (A[j] < A[smallest])
smallest = j;
}
swap(A, i, smallest);
}
}
The good ones (Ο(NlogN)):
void sort(double A[], int low, int high)
{
if (low >= high)
return;
pivot = low;
i = low + 1;
j = high;
// throw smaller ones to pivot's left
// and larger ones to pivot's right
while (i <= j) {
if (A[i] < A[pivot]) {
swap(A, i, pivot);
pivot = i;
i = pivot + 1;
} else {
swap(A, i, j);
j = j - 1;
}
}
// sort the pile with the smaller numbers
sort(A, low, pivot-1);
// sort the pile with the larger numbers
sort(A, pivot+1, high);
}
void sort(double A[], int low, int high)
{
if (low >= high)
return;
// divide the pile into two piles
mid = (low + high)/2
// sort the left pile
sort(A, low, mid);
// sort the right pile
sort(A, mid+1, high);
// merge the two sorted piles into one sorted pile
double B[high-low+1];
i = low;
j = mid+1;
k = 0;
while (i <= mid && j <= high) {
if (A[i] < A[j]) {
B[k] = A[i];
i++;
} else {
B[k] = A[j];
j++;
}
k++;
}
while (i <= mid) {
B[k] = A[i];
i++; k++;
}
while (j <= high) {
B[k] = A[j];
j++; k++;
}
for(i = low, k = 0; i <= high; i++, k++)
A[i] = B[k];
}
void sort(double A[], int N)
{
// max heap insert
for(i = 1; i < N; i++) {
j = i;
parent = (i-1)/2;
while (j > 0 && A[j] > A[parent]) {
swap(A, j, parent);
j = parent;
parent = (j-1)/2;
}
}
// extract from max heap
// so the numbers are sorted from smallest to largest
bool stop;
for(i = N-1; i > 0; i--) {
swap(A, 0, i);
j = 0;
child = j*2+1;
stop = (child >= i);
while (!stop) {
if (child+1 < i && A[child] < A[child+1])
child = child+1;
if (A[j] < A[child]) {
swap(A, j, child);
j = child;
child = j*2+1;
stop = (child >= i);
} else {
stop = true;
}
}
}
}
void sort(double A[], int N)
{
gap = N/2;
while (gap >= 1) {
for(i = gap; i < N; i++) {
j = i;
k = j - gap;
while (k >= 0 && A[j] < A[k]) {
swap(A, j, k);
j = k;
k = j - gap;
}
}
gap = gap/2;
}
}
The unconventional ones:
void sort(int A[], int N)
{
int smallest = min(A); // the smallest number in A
int largest = max(A); // the largest number in A
int size = largest-smallest+1;
bool B[size];
for(i = 0; i < size; i++)
B[i] = false;
for(i = 0; i < N; i++) {
B[A[i]-smallest] = true;
}
i = 0;
for(j = 0; j < size; j++) {
if (B[j]) {
A[i] = j+smallest;
i++;
}
}
}
void sort(int A[], int N)
{
int largest = max(A); // the largest number in A
Queue buckets[10];
factor = 1;
while (factor < largest) {
for(i = 0; i < N; i++) {
buckets[A[i]/factor%10].enqueue(A[i]);
}
i = 0;
for(j = 0; j < 10; j++) {
while (!buckets[j].isEmpty()) {
A[i] = buckets[j].dequeue();
i++;
}
}
factor = factor * 10;
}
}