Make a program in C++ that: Asks a user to enter 20 grades. Each grade is put in
ID: 3688832 • Letter: M
Question
Make a program in C++ that:
Asks a user to enter 20 grades. Each grade is put into a slot in an array. Print out the original values.
Sort the grades, using a bubble sort, from highest grade to lowest grade.
Then print out the sorted grades.
Note: The traditional bubble sort is not efficient enough for large arrays. Make the following simple modifications to improve its performance.
1. After the first pass, the largest number is guaranteed to be in the highest-numbered element of the array; after the second pass, the two highest numbers are “in place,” and so on. Instead of making nine comparisons on every pass, modify the bubble sort to make eight comparisons on the second pass, seven on the third pass and so on. (This will match the Wikipedia version)
2. The data in the array may already be in the proper or near-proper order, so why make nine passes if fewer will suffice? Modify the sort to check at the end of each pass whether any swaps have been made. If none has been made, then the data must already be in the proper order, so the program should terminate. If swaps have been made, then at least one more pass is needed.
Explanation / Answer
// C++ Optimized implementation of Bubble sort
#include <iostream>
#include <stdio.h>
using namespace std;
void swap(int *xp, int *yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}
// An optimized version of Bubble Sort
void bubbleSort(int arr[], int n)
{
int i, j;
bool swapped;
for (i = 0; i < n-1; i++)
{
swapped = false;
for (j = i; j < n-1; j++) // j will start from i to reduce the number of comparisons ,1st modification
{
if (arr[i] < arr[j+1])
{
swap(&arr[i], &arr[j+1]);
swapped = true;
}
}
// IF no two elements were swapped by inner loop, then break
//check at the end of each pass whether any swaps have been made.
//If none has been made, then the data must already be in the proper order, so the program should terminate.
//If swaps have been made, then at least one more pass is needed.
if (swapped == false)
break;
}
}
/* Function to print an array */
void printArray(int arr[], int size)
{
int i;
for (i=0; i < size; i++)
cout << arr[i] << " ";
cout <<endl;
}
// Driver program to test above functions
int main()
{
int arr[20];
cout << "Enter elements of array: ";
for (int i = 0; i < 20; ++i) cin >> arr[i];
int n = 20;
printArray(arr, n);
bubbleSort(arr, n);
printf("Sorted array: ");
printArray(arr, n);
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.