In: Computer Science
In C++
Prototype your 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.
Please find the code below::::
#include <iostream>
using namespace std;
int bubbleSort(int bubble_el[20],int n)
{
int i, j;
int count = 0;
for (i = 0; i < n - 1; i++)
{
for (j = 0; j < n - i - 1; j++)
{
if (bubble_el[j] > bubble_el[j + 1])
{
count++;
int t = bubble_el[j];
bubble_el[j] = bubble_el[j + 1];
bubble_el[j + 1] = t;
}
}
}
return count;
}
int selectionSort(int sel_el[20],int n)
{
int count = 0;
int i, j;
for (i = 0; i < n; i++)
{
for (j = i; j < n; j++)
{
if (sel_el[i] > sel_el[j])
{
count++;
int temp = sel_el[i];
sel_el[i] = sel_el[j];
sel_el[j] = temp;
}
}
}
return count;
}
int main()
{
srand(time(NULL));
int size =20;
int rand_val;
int bubble_el[size];
int sel_el[size];
for (int j = 0; j < size; j++)
{
rand_val = rand() % 100;
bubble_el[j] = rand_val;
sel_el[j] = rand_val;
}
int count1=bubbleSort(bubble_el,size);
int count2=selectionSort(sel_el,size);
cout<<"Number of exchange in bubble sort :
"<<count1<<endl;
cout<<"Number of exchange in selection sort :
"<<count2<<endl;
return 0;
}
output: