Question: Consider the following code for a Bubble Sort application: ------------------- #include #include using namespace std; using std::setw; using std::cout; using std::endl; using std::size_t; int main()
Consider the following code for a Bubble Sort application:
-------------------
#include
#include
using namespace std;
using std::setw;
using std::cout;
using std::endl;
using std::size_t;
int main() {
const short arraySize = 10;
short arr [ arraySize ] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 };
short hold;
cout << "Data items in original order:" << endl;
for ( size_t i = 0; i < arraySize; ++i ) {
cout << setw ( 4 ) << arr [ i ];
} // for i
for ( size_t pass = 0; pass < arraySize; ++pass ) {
for ( size_t j = 0; j < arraySize; ++j ) {
if ( arr [ j ] > arr [ j + 1 ] ) {
hold = arr [ j ];
arr [ j ] = arr [ j + 1 ];
arr [ j + 1 ] = hold;
} // if
} // for j
} // for pass
cout << endl << "Data items in ascending order:" << endl;
for ( size_t i = 0; i < arraySize; ++i ) {
cout << setw ( 4 ) << arr [ i ];
} // for i
cout << endl;
return 0;
} // BubbleSort
--------------------
1. Rewrite this code, using modular programming style, and correcting any errors if necessary. [50]
2. Optimize the algorithm by making the following modifications:
(a) After the first pass, the largest number is guaranteed to be in the highest-numbered element in the array; after the second pass, the two highest numbers are in place, and so on. Instead of comparing every pair on every pass, modify the algorithm to make as few comparisons as necessary on each pass. [10]
(b) Modify the algorithm to check at the end of each pass if any swaps have been made. If none have been made, the data must already be in the proper order, so the program should terminate. Observe the single-exit point rule when making this modification. [10]
3. Insert appropriate statements in your code to output the state of the array after every pass. [30]
4. Submit: (i) both hardcopy and softcopy of your source code; (ii) output of the program.
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
