In: Computer Science
Write a program that uses two identical arrays of at least 25 integers. It should call a function that uses the bubble sort algorithm to sort one of the arrays in descending order. The function should keep a 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 array. It should also keep count of the number of exchanges it makes. Display these values on the screen.
/* * C Language Program * Count number of swaps in bubble sort and selectoin sort */ #include <stdio.h> #include <time.h> #include <stdlib.h> #define MAX 25 int bubbleSort(int array[], int count); int selectionSort(int arr[], int N); int main() { int arrayFirst[MAX]; int arraySecond[MAX]; int bubbleSwap, selectionSwap; int i, temp; srand(time(NULL)); for (i = 0; i < MAX; i++) { temp = rand() % 100; arrayFirst[i] = temp; arraySecond[i] = temp; } bubbleSwap = bubbleSort(arrayFirst, MAX); selectionSwap = selectionSort(arraySecond, MAX); printf("Total number of swaps in bubble sort: %d\n", bubbleSwap); printf("Total number of swaps in selection sort: %d\n", selectionSwap); return 0; } int bubbleSort(int arr[], int N) { int i, j, temp; int swaps = 0; for (i = 0; i < N - 1; ++i) { for (j = 0; j < N - 1 - i; ++j) { if (arr[j] > arr[j+1]) { temp = arr[j + 1]; arr[j + 1] = arr[j]; arr[j] = temp; swaps++; } } } return swaps; } int selectionSort(int arr[], int N) { int i, j; int temp, min_indx; int swaps = 0; for(i = 0; i < N; i++) { min_indx = i; for(j = i+1; j < N; j++) { if(arr[min_indx] > arr[j]) min_indx = j; } temp = arr[min_indx]; arr[min_indx] = arr[i]; arr[i] = temp; swaps++; } return swaps; } /* Program ends here */
Note: No language was mentioned, hence the program is written in C, for change of language drop a comment.