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.

Respuesta :

Answer:

The C++ code is given below

Explanation:

#include<iostream>

using namespace std;

void swap(int &a,int &b)

{

int temp = a;

a = b;

b = temp;

}

int bubbleSort(int *arr,int size)

{

int count = 0;

for (int i = 0; i < size-1; i++)

{

for (int j = 0; j < size-i-1; j++)

{

if (arr[j] > arr[j+1])

{

swap(arr[j],arr[j+1]);

count++;

}

}

}

 

return count;

}

int selectionSort(int *arr,int size)

{

int position,count = 0;

for (int i = 0; i < size-1; i++)

{

position = i;

for (int j = i+1; j<size; j++)

{

if (arr[position] > arr[j])

position = j;

}

if (position != i)

{

swap(arr[i],arr[position]);

count++;

}

}

return count;

}

void printArray(int *arr,int size)

{

for(int i=0;i<size;i++)

cout << arr[i] << " " ;

cout << endl;

}

int main()

{

int arr[20] = {1,3,4,2,6,7,8,5,12,13,14,15,9,10,11,20,19,18,17,16};

int arr1[20] = {1,3,4,2,6,7,8,5,12,13,14,15,9,10,11,20,19,18,17,16};

 

cout << "Array Before sorting : ";

printArray(arr,20);

 

int count = bubbleSort(arr,20);

 

cout << "Array After sorting : ";

printArray(arr,20);

 

cout << "Array Before sorting : ";

printArray(arr1,20);

 

int count1 = selectionSort(arr1,20);

 

cout << "Array After sorting : ";

printArray(arr1,20);

 

cout << "Number of exchanges in bubble sort is : " << count << endl;

cout << "Number of exchanges in selection sort is : " << count1 << endl;

return 0;

}