(Bubble Sort) In the bubble sort algorithm, smaller values gradually “bubble” their way up- ward to the top of the array like air bubbles rising in water, while the larger values sink to the bot- tom. The bubble sort makes several passes through the array. On each pass, successive pairs of elements are compared. If a pair is in increasing order (or the values are identical), we leave the

values as they are. If a pair is in decreasing order, their values are swapped in the array. Write a program that sorts an array of 10 integers using bubble sort.

What will be an ideal response?


```
// This program sorts an array's values into ascending order.
#include
#include
using namespace std;

int main()
{
const int arraySize = 10; // size of array a
int a[ arraySize ] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 };
int hold; // temporary location used to swap array elements

cout << "Data items in original order\n";

// output original array
for ( int i = 0; i < arraySize; i++ )
cout << setw( 4 ) << a[ i ];

// bubble sort
// loop to control number of passes
for ( int pass = 0; pass < arraySize - 1; pass++ )
{
// loop to control number of comparisons per pass
for ( int j = 0; j < arraySize - 1; j++ )
{
// compare side-by-side elements and swap them if
// first element is greater than second element
if ( a[ j ] > a[ j + 1 ] )
{
hold = a[ j ];
a[ j ] = a[ j + 1 ];
a[ j + 1 ] = hold;
} // end if
} // end for
} // end for

cout << "\nData items in ascending order\n";

// output sorted array
for ( int k = 0; k < arraySize; k++ )
cout << setw( 4 ) << a[ k ];

cout << endl;
} // end main
```
Data items in original order
2 6 4 8 10 12 89 68 45 37
Data items in ascending order
2 4 6 8 10 12 37 45 68 89

Computer Science & Information Technology

You might also like to view...

The ________ multithreading header contains classes and class templates for ensuring mutually exlusive access to resources shared among threads in an application.

a. b. c. d.

Computer Science & Information Technology

In Python, a(n) ____________________ is required punctuation for the end of an IF statement.

Fill in the blank(s) with the appropriate word(s).

Computer Science & Information Technology

Answer the following statements true (T) or false (F)

The pipe (|) character redirects the output of the command preceding it.

Computer Science & Information Technology

To highlight multiple tables, click each table by holding the ________ key

Fill in the blank(s) with correct word

Computer Science & Information Technology