(Bubble Sort Enhancements) The bubble sort described in Exercise 6.11 is inefficient for large arrays. Make the following simple modifications to improve the performance of the bubble sort:

a) 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.
b) The data in the array may already be in the proper order or near-proper order, so why make nine passes if fewer will suffice? Modify the sort to check at the end of each pass if any swaps have been made. If none have 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.


```
#include
#include
using namespace std;

int main()
{
const int SIZE = 10; // size of array
int a[ SIZE ] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 };
int hold;
int numberOfComp = 0; // number of comparisons made
int comp; // used to control for loop and for subscripts

// display original, unsorted array
cout << "Data items in original order\n";
for ( int i = 0; i < SIZE; ++i )
cout << setw( 4 ) << a[ i ];

cout << "\n\n";

// begin sorting the array
for ( int pass = 1; pass < SIZE; pass++ )
{
cout << "After pass " << pass - 1 << ": ";

// traverse and compare unsorted part of array
for ( comp = 0; comp < SIZE - pass; comp++ )
{
numberOfComp++;

// compare adjacent array elements
if ( a[ comp ] > a[ comp + 1 ] )
{
hold = a[ comp ];
a[ comp ] = a[ comp + 1 ];
a[ comp + 1 ] = hold;
} // end if

cout << setw( 3 ) << a[ comp ];
} // end inner for

cout << setw( 3 ) << a[ comp ] << '\n'; // print last array value
} // end outer for

// diplay array in sorted order
cout << "\nData items in ascending order\n";

for ( int j = 0; j < SIZE; j++ )
cout << setw( 4 ) << a[ j ];

// display the number of comparisons made
cout << "\nNumber of comparisons = " << numberOfComp << endl;
} // end main
```

Computer Science & Information Technology

You might also like to view...

The __________ process involves asking users to prove their identity.

a. authorization b. indexing c. authentication d. accounting

Computer Science & Information Technology

A(n) ________ query is a query where the dataset is added to an existing table

A) update B) delete C) make table D) append

Computer Science & Information Technology

________ is used to create a backup of notebooks in OneNote

Fill in the blank(s) with correct word

Computer Science & Information Technology

When the text is found with the Reading Highlighted option, the yellow background color will appear on the printed copy if you choose to print the document

Indicate whether the statement is true or false

Computer Science & Information Technology