The results:
The array a:
0
1
2
3
4
5
The codes:
//selection sort
#include<iostream>
#include<iomanip>
using namespace std;
void selection_sort(int a[], int n);
void display_selection(int a[], int n);
void swap_selection(int &n1, int &n2); //Remember that n1 and n2 are the arguments that cannot be transferred
int main()
{
int a[] = {2,3,4,5,0,1};
int n = 6;
selection_sort(a,n);
display_selection(a,n);
return 0;
}
void selection_sort(int a[], int n)
{
int k;
for(int i=0; i<n; i++){
k = i;
for(int j=i+1; j<n; j++){
if(a[j]<a[k]){
k = j;
}
}
swap_selection(a[i], a[k]);
}
}
void display_selection(int a[], int n)
{
cout << "The array a:"<<endl;
for(int i=0; i<n; i++){
cout <<setw(3) <<a[i] <<endl;
}
}
void swap_selection(int &n1, int &n2)
{
int temp = n1;
n1 = n2;
n2 = temp;
}
The outputs:
The original array is:
The array a :
4 6 2 6 53 2 6 12
The array after the selection is:
The array a :
2 2 4 6 6 6 12 53
The codes:
// obtain the results from the selection sort function by recrusive methods
#include<iostream>
#include<iomanip>
void swap(int &i, int &j);
void selectionSort(int a[], int n);
void displaySelection(int a[], int n);
using namespace std;
int main()
{
int a[] = {4,6,2,6,53,2,6,12};
int n = sizeof(a) / sizeof(a[0]);
cout << "The original array is:" <<endl;
displaySelection(a, n);
selectionSort(a, n);
cout << "\nThe array after the selection is:" <<endl;
displaySelection(a, n);
return 0;
}
void selectionSort(int a[], int n)
{
if(n ==1){
return ;
}
selectionSort(a,n-1);
if(a[n-1] < a[n-2]){
swap(a[n-1],a[n-2]);
}
selectionSort(a,n-1);
}
void displaySelection(int a[], int n)
{
cout <<"The array a : " << endl;
for(int i = 0; i < n; i++){
cout << setw(4) << a[i];
}
}
void swap(int &i, int &j)
{
int temp;
temp = i;
i = j;
j = temp;
}