In: Computer Science
Implement a program in C++ that does the following:
#include<iostream>
using namespace std;
//for maintaining array size
#define SIZE 10
void selection_sort(int arr[]){
int min_val_idx, temp;
for(int i = 0; i < SIZE-1; i++){
min_val_idx = i; //for maintaining index of minimum element
for(int j = i+1; j < SIZE; j++)
if(arr[j] < arr[min_val_idx])
min_val_idx = j;
//swaping min element with current left most element
temp = arr[min_val_idx];
arr[min_val_idx] = arr[i];
arr[i] = temp;
}
}
int main(){
//declare array
int arr[SIZE];
cout<<"Please enter 10 numbers\n";
//input from terminal
for(int i = 0;i<SIZE;i++)
cin>>arr[i];
cout<<"Array before sorting\n";
//print unsorted array
for(int i = 0;i<SIZE;i++)
cout<<arr[i]<<" ";
cout<<"\n";
//calling selection sort function
selection_sort(arr);
cout<<"Array after sorting\n";
//print sorted array
for(int i = 0;i<SIZE;i++)
cout<<arr[i]<<" ";
cout<<"\n";
return 0;
}
Sample Ouput:
To compile: g++ <filename>
To run: ./a.out
Code is well commented. If you have any query or doubts then let me know in the commnets. Thanks!