C++ || Snippet – Sort An Integer Array Using Bubble Sort – Print Each Pass & Total Number Of Swaps

This is a program which has no functionality, but displays the sorting of an integer array through the use of the bubble sort algorithm.

This program sorts the values of a one-dimensional array in ascending order using bubble sort. It also prints the total number of passes thru each iteration

REQUIRED KNOWLEDGE FOR THIS SNIPPET

Integer Arrays
Bubble Sort
Setw

QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

Once compiled, you should get this as your output

Original array values
0 1 3 95 2 4 6 10 15 4 17 35
---------------------------------------------------------------
Array after bubble sort pass #1
0 1 3 2 4 6 10 15 4 17 35 95

Array after bubble sort pass #2
0 1 2 3 4 6 10 4 15 17 35 95

Array after bubble sort pass #3
0 1 2 3 4 6 4 10 15 17 35 95

Array after bubble sort pass #4
0 1 2 3 4 4 6 10 15 17 35 95
---------------------------------------------------------------
The current sorted array
0 1 2 3 4 4 6 10 15 17 35 95
---------------------------------------------------------------
Total Swaps: 12
Total Passes: 4

Was this article helpful?
👍 YesNo

Leave a Reply