In: Computer Science
Need hep with this c++ program
Declare an array of integers of size 8 and initialize it with any non-duplicate integer values you like. Don’t enter the values in any order. Print the unsorted array. Sort the array using selection sort or insertion sort in descending order. Print what sort you are using. Write any additional functions that you need for sorting. Keep monitoring the number of comparisons and number of swaps performed while sorting. Report both after sorting. Print the sorted array.
#include<iostream>
using namespace std;
int main()
{
int arr[8];
int i;
cout<<"Enter 8 numbers : ";
// traverse the array
for( i = 0 ; i < 8 ; i++ )
// get user input
cin>>arr[i];
cout<<"Array : ";
// display array elements
for( i = 0 ; i < 8 ; i++ )
cout<<arr[i]<<" ";
int j, min, x;
int swaps = 0;
int comparisons = 0;
// traverse the array
for (i = 0; i < 7; i++)
{
// store the index of the smallest element
min = i;
// traverse the array from the element after i till the end
for (j = i + 1; j < 8; j++)
{
comparisons++;
// if the current element is smaller than the min element
if (arr[j] > arr[min])
min = j;
}
// Swap first element and min
x = arr[min];
arr[min] = arr[i];
arr[i] = x;
swaps++;
}
cout<<"\nSorted Array : ";
// display array elements
for( i = 0 ; i < 8 ; i++ )
cout<<arr[i]<<" ";
cout<<"\nNo of swaps : "<<swaps<<endl;
cout<<"No of comparisons : "<<comparisons<<endl;
return 0;
}
Sample Output
