Consider sorting n numbers stored in array A by first finding the smallest element of A and putting it in the first entry of another array B. Then find the second smallest element of A and put it in the second entry of B. Continue in this manner for the n elements of A. Write pseudocode for this algorithm, which is known as selection sort. Give the best-case and worst-case running times of selection sort in θ-notation.
/*
* Sorting n numbers stored in array A by finding the smallest element of
* unsorted part, and putting it in the end of sorted part.
*
* The best-case running times in θ-notation is θ(n^2).
* The worst-case running times in θ-notation is θ(n^2).
*/
void Algorithms::selectionSort(int A[], int n) {
int min;
for (int i = 0; i < n; i++) {
min = i;
for (int j = i + 1; j < n; j++) {
if (A[j] < A[min]) {
min = j;
}
}
if (min > i) {
// switch A[i] and A[min]
int temp = A[i];
A[i] = A[min];
A[min] = temp;
// Alternative 1 for switching A[i] and A[min]
// A[i] ^= A[min];
// A[min] ^= A[i];
// A[i] ^= A[min];
// alternative 2 for switching A[i] and A[min]
// A[i] += A[min];
// A[min] = A[i] - A[min];
// A[i] = A[i] - A[min];
}
}
}
/*
* Sorting n numbers stored in array A by finding the smallest element of
* unsorted part, and putting it in the end of sorted part.
*
* The best-case running times in θ-notation is θ(n^2).
* The worst-case running times in θ-notation is θ(n^2).
*/
void Algorithms::selectionSort(int A[], int n) {
int min;
for (int i = 0; i < n; i++) {
min = i;
for (int j = i + 1; j < n; j++) {
if (A[j] < A[min]) {
min = j;
}
}
if (min > i) {
// switch A[i] and A[min]
int temp = A[i];
A[i] = A[min];
A[min] = temp;
// Alternative 1 for switching A[i] and A[min]
// A[i] ^= A[min];
// A[min] ^= A[i];
// A[i] ^= A[min];
// alternative 2 for switching A[i] and A[min]
// A[i] += A[min];
// A[min] = A[i] - A[min];
// A[i] = A[i] - A[min];
}
}
}