Question
Bubble Sort Enhancement After the first pass, the largest number is guaranteed to be in the highest indexed element in the array. After the second
Bubble Sort Enhancement
After the first pass, the largest number is guaranteed to be in the highest indexed element in the array. After the second pass the two largest numbers are in place. Modify the bubble sort to make less comparisons on each pass, thus increasing the efficiency of the algorithm
#include
#include
#include
using namespace std;
int genrand(int minv,int maxv)
{
return (rand()%(maxv-minv)+minv);
}
void generate_int_rnd_number(int *numbers, int min_value,int max_value, int num)
{
cout << "Random Numbers from " << min_value << " to " << max_value << endl;
for (int i = 0; i < num; i++) {
numbers[i]=genrand(min_value,max_value);
cout << numbers[i] << " ";
}
cout << endl;
}
int bubblesort(int *myArray, int num)
{
int temp = 0;
int swpcount = 0;
for(int i = 0; i < 10; i++) {
for (int j = 0; j < 9; j++) {
if (myArray[j] > myArray[j+1]) {
temp = myArray[j];
myArray[j] = myArray[j+1];
myArray[j+1] = temp;
swpcount++;
}
}
}
return swpcount;
}
int main()
{
int myArray[10];
int swpcount;
float sum = 0;
int n;
srand(time(NULL));
cout << "Enter the number of time you want sort numbers from 10 to 50" << endl <<
"For average swap count calculation" << endl;
cin >> n;
for (int i = 0; i < n; i++) {
/* Here, the first 10 and 50 are the range of random numbers
* and the next argument is the array size
*/
generate_int_rnd_number(myArray, 10, 50, 10);
swpcount = bubblesort(myArray, 10);
sum += swpcount;
/*Print the sorted array*/
for (int i = 0; i < 10; i++){
cout << myArray[i] << "\t";
}
cout << endl;
cout << "Total number of swaps " << swpcount << endl;
}
cout << "Average number of swaps " << sum/n << endl;
return 0;
}
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started