// Nathanael Schwartz CS1A Chapter 8, P. 515, #1
//
/*******************************************************************************
*
* BUBBLE SORT AND SELECTION SORT WITH PASS PRINTS
* _____________________________________________________________________________
* This program uses two identical arrays of eight integers. It displays the
* contents of the first array, then sorts it using a bubble sort algorithm. The
* program prints the array contents after each pass of the bubble sort.
* The program then displays the contents of the second array, then sorts it
* using a selection sort algorithm, printing the array contents after each pass.
* _____________________________________________________________________________
* INPUT
* arr1 : Array to be sorted using bubble sort
* arr2 : Array to be sorted using selection sort
*
* OUTPUT
* The contents of the arrays after each pass of the respective sorting
* algorithm, showing the progress of the sorting.
*
******************************************************************************/
#include <iostream>
using namespace std;
// Bubble Sort function with pass prints
void bubbleSort(int arr[], int size) {
int exchangeCount = 0;
for (int i = 0; i < size - 1; ++i) {
for (int j = 0; j < size - i - 1; ++j) {
if (arr[j] > arr[j + 1]) {
// Swap the elements
swap(arr[j], arr[j + 1]);
++exchangeCount;
}
}
// Print the array after each pass
cout << "After pass " << i + 1 << ": ";
for (int k = 0; k < size; ++k) {
cout << arr[k] << " ";
}
cout << endl;
}
}
// Selection Sort function with pass prints
void selectionSort(int arr[], int size) {
int exchangeCount = 0;
for (int i = 0; i < size - 1; ++i) {
int minIndex = i;
for (int j = i + 1; j < size; ++j) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
// Swap the elements if necessary
if (minIndex != i) {
swap(arr[i], arr[minIndex]);
++exchangeCount;
}
// Print the array after each pass
cout << "After pass " << i + 1 << ": ";
for (int k = 0; k < size; ++k) {
cout << arr[k] << " ";
}
cout << endl;
}
}
int main() {
// Initialize two identical arrays of integers
int arr1[8] = {12, 3, 5, 7, 19, 2, 13, 18};
int arr2[8] = {12, 3, 5, 7, 19, 2, 13, 18};
// Display the first array
cout << "Original array for bubble sort: ";
for (int i = 0; i < 8; ++i) {
cout << arr1[i] << " ";
}
cout << endl;
// Perform bubble sort and print the array after each pass
bubbleSort(arr1, 8);
// Display the second array
cout << "\nOriginal array for selection sort: ";
for (int i = 0; i < 8; ++i) {
cout << arr2[i] << " ";
}
cout << endl;
// Perform selection sort and print the array after each pass
selectionSort(arr2, 8);
return 0;
}