diff --git a/guide/english/algorithms/sorting-algorithms/selection-sort/index.md b/guide/english/algorithms/sorting-algorithms/selection-sort/index.md index 95db5011e2..92db28b879 100644 --- a/guide/english/algorithms/sorting-algorithms/selection-sort/index.md +++ b/guide/english/algorithms/sorting-algorithms/selection-sort/index.md @@ -21,49 +21,67 @@ Selection sort always takes the same number of key comparisons — N(N − 1)/2. ### Implementation in C/C++ -#### Iterative Implementation -```C -for(int i = 0; i < n-1; i++) -{ - int min_index = i; - - - for(int j = i +1; j < n; j++) - { - if(a[j] < a[min_index]) - { - - min_index = j; - } - } - - swap(&a[i], &a[min_index]); +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. + +```cpp +#include +#include +using namespace std; + +template +void print_array(T const(&arr)[n]) { + for (size_t i = 0; i < n; i++) + std::cout << arr[i] << ' '; + cout << "\n"; } -``` - -#### Recursive Implementation -```C -int minIndex(int a[], int i, int j) -{ - if (i == j) return i; +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; +} - 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]); - +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_element = a[i]; + for (int j = i + 1; j < n; j++) + { + if (a[j] < min_element) + { + min_element = a[j]; + min_index = j; + } + } + swap(a[i], a[min_index]); + } +} + +int main() { + int recurArr[6] = { 100,35, 500, 9, 67, 20 }; + int iterArr[5] = { 25, 0, 500, 56, 98 }; + + 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 + + cout << "Iterative Selection Sort" << "\n"; + print_array(iterArr); // 25 0 500 56 98 + iterSelectionSort(iterArr, 5); + print_array(iterArr); // 0 25 56 98 500 +} ``` ### Implementation in JavaScript @@ -150,7 +168,6 @@ end * Time Complexity: O(n2) * Sorting in Place: Yes * Stable: No - ### Visualization * [USFCA](https://www.cs.usfca.edu/~galles/visualization/ComparisonSort.html) * [HackerEarth](https://www.hackerearth.com/practice/algorithms/sorting/selection-sort/visualize/)