Wednesday, April 18, 2007

Selection Sort

Another easy sorting algorithm, this sort iterates through the array and swaps two elements if the first one is higher than the second one. The logic is to select the smallest available element from the un-sorted stack and put it in the current place.


The code it quite simple, so here we go

#include <iostream>
using namespace std;
int arr[10], mini;
int main(){
cout << "Enter 10 numbers" << endl;
for(int i = 0; i < 10; i++) cin >> arr[i];
for(int i = 0; i < 10-1; i++){
mini = i;
for(int j = i+1; j < 10; j++){
mini = arr[j] < arr[mini] ? j : i;
swap(arr[i], arr[mini]);
}
}
cout << "Sorted numbers are :" << endl;
for(int i = 0; i < 10; i++) cout << arr[i] << " ";
cout << endl;
return 0;
}


2 comments:

Dante said...

Thanks for the code :D

Sifaan said...

Why does the swap have to be inside the inner for loop?