Selection Sort


1. Algorithm

The idea of the algorithm: the element at row n a0, a1, ..., an-1
- Select the sequence a0, a1, ..., an-1 the smallest element and permutation lock it with a0.
- Select the sequence a1, a2, ..., an-1 the smallest element and permutation lock it with a1.
- Continue like that after we obtain n -1 step unordered list.

Ex Bubble Sort

2. Source Code:

#include <iostream>
#include <conio.h>
#define max 100
using namespace std;
//Input Array
void InputArray(int A[],int n){
for(int i=0; i<n; i++) {
cout<<"Input element A["<<i<<"] =";
cin>>A[i];
}
}

//Print Array
void PrintArray(int A[],int n){
cout<<endl;
for(int i=0; i<n; i++)
cout<<A[i]<<"\t";
}
//Swap 2 elements
void Swap(int &a,int &b) {
int temp = a;
a = b;
b = temp;
}
//Selection Sort Algorithm
void SelectionSort(int A[],int n) {
int min;
for(int i=0; i<n -1; i++) {
min = i;
for(int j=i+1; j<n; j++)
if(A[min]>A[j])
min = j;
if(min != i)
Swap(A[i],A[min]);
}
}
//Main Function
int main() {
int A[max],n;
cout<<"Input number of array:";
cin>>n;
InputArray(A,n);
cout<<"\nOriginal Array:";
PrintArray(A,n);
cout<<endl;
SelectionSort(A,n);
cout<<"\nSorted Array:";
PrintArray(A,n);
getch();
return 0;
}

3. Result:

selection_sort_result


Advertisements