In: Computer Science
In C++, write a program that uses two identical arrays of ten randomly ordered integers. It should display the contents of the first array, then call a function to sort it using the most efficient descending order bubble sort, modified to print out the array contents after each pass of the sort. Next the program should display the contents of the second array, then call a function to sort it using descending order selection sort, modified to print out the array contents after each pass of the sort.
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
const int SIZE = 10;
void print(int arr[]) // display array
{ cout<<"{ ";
for (int i = 0; i < SIZE; i++)
{
cout << arr[i] << "
";
}
cout<<" }";
cout << endl;
}
void bubbleSort(int arr[]) //bubble sorting
{
int temp;
bool swap;
do
{ swap = false;
for (int i = 0; i < (SIZE -
1); i++)
{
if (arr[i] <
arr[i + 1]) // compare element with every next and check if current
is lesser update it
{
temp = arr[i]; //swap them
arr[i] = arr[i + 1];
arr[i + 1] = temp;
swap = true;
}
print(arr);
}
} while (swap);
}
void selectionSort(int arr[])
{
int curr;
int large;
for (int i = 0; i < (SIZE - 1); i++)
{
curr = i;
large = arr[i];
for (int j = i + 1; j < SIZE;
j++)
{
if (arr[j] >
large) //compare if current is lesser than next swap them
{
large = arr[j];
curr = j;
}
}
arr[curr] = arr[i];
arr[i] = large;
print(arr);
}
}
int main()
{
srand(time(NULL)); //setting random number
int Array1[SIZE];
int Array2[SIZE];
for(int i=0;i<SIZE;i++){
Array1[i]=(rand()%100+1); //set random number from 1 to 100
Array2[i]=(rand()%100+1); // set random number from 1 to 100
}
cout<<":::::::::: 1st Array Elements
::::::::::"<<endl;
print(Array1);
cout<<":::::::::: ARRAY 1 data after every
Bubble Sort ::::::::::"<<endl;
bubbleSort(Array1);
cout<<":::::::::: 2nd Array Elements
::::::::::"<<endl;
print(Array2);
cout<<":::::::::: SELECTION SORT IN DESCENDING
ORDER ::::::::::"<<endl;
selectionSort(Array2);
return 0;
}
OUTPUT:
IF YOU HAVE ANY QUERY PLEASE COMMENT DOWN BELOW
PLEASE GIVE A THUMBS UP