In: Computer Science
In C++
prototype functions above "main" and define them below "main";
Write a program that uses two identical arrays of at least 20 integers. It should call a function that uses the bubble sort algorithm to sort one of the arrays in ascending order. The function should keep count of the number of exchanges it makes. The program then should call a function that uses the selection sort algorithm to sort the other arrays. It should also keep count of the number of exchanges it makes. Display these values on the screen.
`Hey,
Note: Brother in case of any queries, just comment in box I would be very happy to assist all your queries
#include <iostream>
using namespace std;
int BubbleSort(int values[], int numValues){
int i, j;
int temp;
int swaps=0;
// outer loop to travel through the all elements
for (i = 0; i < numValues - 1; i++) {
// inner loop to compare the outer loop elements
for (j = 0; j < numValues - i - 1; j++)
// if element at j< than j+1 than swap both
if (values[j] > values[j + 1]) {
// swap logic
temp = values[j];
values[j] = values[j+1];
values[j+1] = temp;
swaps++;
}
}
return swaps;
}
int SelectionSort(int values[], int numValues)
{
int swaps=0;
// One by one move boundary of unsorted subarray
for (int i = 0; i < numValues-1; i++)
{
// Find the minimum element in unsorted array
int min_idx = i;
for (int j = i+1; j < numValues; j++)
if (values[j] < values[min_idx])
min_idx = j;
// Swap the found minimum element with the first
// element
swaps++;
int temp = values[min_idx];
values[min_idx] = values[i];
values[i] = temp;
}
return swaps;
}
void printArray(int arr[],int n)
{
for(int i=0;i<n;i++)
{
cout<<arr[i]<<" ";
}
cout<<endl;
}
int main() {
int arr1[]={20,10,15,14,29,28,30,39,32,45,98,78,56,91,54,12,45,65,76,90};
int
arr2[]={20,10,15,14,29,28,30,39,32,45,98,78,56,91,54,12,45,65,76,90};
cout<<"Original array 1: ";
printArray(arr1,20);
int s1=BubbleSort(arr1, 20);
cout<<"After bubble sort array 1: ";
printArray(arr1,20);
cout<<"Swap count using BubbleSort :
"<<s1<<endl;
cout<<"Original array 2: ";
printArray(arr2,20);
int s2=SelectionSort(arr2, 20);
cout<<"After Selection sort array 2: ";
printArray(arr2,20);
cout<<"Swap count using SelectionSort : "<<s2<<endl;
}
Kindly revert for any queries
Thanks.