I wrote a selection sort program in C++. I have checked and rechecked the code, but the logic is perfectly fine. But the code is not sorting the array properly:
// Selection Sort
#include <iostream>
using namespace std;
inline void swap( int& x, int& y) {
int temp = x;
x = y;
y = temp;
}
int main() {
const int n = 10;
int list[n];
string line(14, '-');
cout << '\n' << line << "\nSelection Sort\n" << line << '\n';
cout << "Enter " << n << " elements:\n";
for( int i = 0; i < n; ++i ) {
cin >> list[i];
}
for( int i = 0; i < n-1; ++i ) {
int small = i;
for( int j = 1; j < n; ++j ) {
if( list[j] < list[small] ) {
small = j;
}
}
if( list[small] < list[i] ) {
swap( list[i], list[small]);
}
}
cout << "Sorted Array:\n";
for( int i = 0; i < n; ++i ) {
cout << list[i] << ' ';
}
return 0;
}
Where am I going wrong? The algorithm of Selection sort is given here: Selection Sort- wikipedia
Sample input with 10 numbers:
7 8 9 10 11 12 13 14 15 16
Output:
7 9 10 11 12 13 14 15 8 16
std::vector.