fix(guide): Fix C++ selection sort algo (#35546)

This commit is contained in:
Manish Giri
2019-04-23 12:48:42 -04:00
committed by Randell Dawson
parent 78777537fa
commit 220c982d52

View File

@ -21,48 +21,66 @@ Selection sort always takes the same number of key comparisons — N(N 1)/2.
### Implementation in C/C++ ### Implementation in C/C++
#### Iterative Implementation The following C++ program contains an iterative as well as a recursive implementation of the Selection Sort algoritm. Both implementations are invoked in the `main()` function.
```C
for(int i = 0; i < n-1; i++) ```cpp
{ #include <iostream>
#include <string>
using namespace std;
template<typename T, size_t n>
void print_array(T const(&arr)[n]) {
for (size_t i = 0; i < n; i++)
std::cout << arr[i] << ' ';
cout << "\n";
}
int minIndex(int a[], int i, int j) {
if (i == j)
return i;
int k = minIndex(a, i + 1, j);
return (a[i] < a[k]) ? i : k;
}
void recurSelectionSort(int a[], int n, int index = 0) {
if (index == n)
return;
int k = minIndex(a, index, n - 1);
if (k != index)
swap(a[k], a[index]);
recurSelectionSort(a, n, index + 1);
}
void iterSelectionSort(int a[], int n) {
for (int i = 0; i < n; i++)
{
int min_index = i; int min_index = i;
int min_element = a[i];
for (int j = i + 1; j < n; j++)
for(int j = i +1; j < n; j++)
{ {
if(a[j] < a[min_index]) if (a[j] < min_element)
{ {
min_element = a[j];
min_index = j; min_index = j;
} }
} }
swap(a[i], a[min_index]);
swap(&a[i], &a[min_index]); }
}
```
#### Recursive Implementation
```C
int minIndex(int a[], int i, int j)
{
if (i == j) return i;
int k = minIndex(a, i + 1, j);
return (a[i] < a[k])? i : k;
} }
int main() {
int recurArr[6] = { 100,35, 500, 9, 67, 20 };
int iterArr[5] = { 25, 0, 500, 56, 98 };
void recurSelectionSort(int a[], int n, int index = 0) cout << "Recursive Selection Sort" << "\n";
{ print_array(recurArr); // 100 35 500 9 67 20
recurSelectionSort(recurArr, 6);
print_array(recurArr); // 9 20 35 67 100 500
if (index == n) return; cout << "Iterative Selection Sort" << "\n";
print_array(iterArr); // 25 0 500 56 98
int k = minIndex(a, index, n-1); iterSelectionSort(iterArr, 5);
print_array(iterArr); // 0 25 56 98 500
if (k != index) swap(a[k], a[index]);
recurSelectionSort(a, n, index + 1);
} }
``` ```
@ -150,7 +168,6 @@ end
* Time Complexity: <b>O(n<sup>2</sup>)</b> * Time Complexity: <b>O(n<sup>2</sup>)</b>
* Sorting in Place: <b>Yes</b> * Sorting in Place: <b>Yes</b>
* Stable: <b>No</b> * Stable: <b>No</b>
### Visualization ### Visualization
* [USFCA](https://www.cs.usfca.edu/~galles/visualization/ComparisonSort.html) * [USFCA](https://www.cs.usfca.edu/~galles/visualization/ComparisonSort.html)
* [HackerEarth](https://www.hackerearth.com/practice/algorithms/sorting/selection-sort/visualize/) * [HackerEarth](https://www.hackerearth.com/practice/algorithms/sorting/selection-sort/visualize/)