//Devin Scheu CS1A Chapter 8, P. 489, #10
//
/**************************************************************
*
* DEMONSTRATE SORTING WITH PRINT AFTER EACH PASS
* ____________________________________________________________
* This program sorts two identical arrays using bubble sort
* and selection sort, printing the array after each pass.
* ____________________________________________________________
* INPUT
* array1 : An array of 8 integers
* array2 : An indentical array of array 1
*
* OUTPUT
* sortedArrays : The arrays printed after each sort pass
*
**************************************************************/
#include <iostream>
#include <iomanip>
using namespace std;
// Function for bubble sort with print after each pass
void bubbleSort(int arr[], int size) {
for (int i = 0; i < size - 1; i++) {
for (int j = 0; j < size - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
// Print after each pass
cout << "Bubble Sort Pass " << (i + 1) << ": ";
for (int k = 0; k < size; k++) {
cout << arr[k] << " ";
}
cout << endl;
}
}
// Function for selection sort with print after each pass
void selectionSort(int arr[], int size) {
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;
}
}
if (minIndex != i) {
int temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
// Print after each pass
cout << "Selection Sort Pass " << (i + 1) << ": ";
for (int k = 0; k < size; k++) {
cout << arr[k] << " ";
}
cout << endl;
}
}
int main () {
//Variable Declarations
const int ARRAY_SIZE = 8; //OUTPUT - Size of the arrays
int array1[ARRAY_SIZE] = {5, 3, 8, 1, 7, 2, 6, 4};//OUTPUT - First array for bubble sort
int array2[ARRAY_SIZE]; //OUTPUT - Second array for selection sort
//Copy array for independent sorting
for (int i = 0; i < ARRAY_SIZE; i++) {
array2[i] = array1[i];
}
//Display First Array
cout << "First Array (before bubble sort): ";
for (int i = 0; i < ARRAY_SIZE; i++) {
cout << array1[i] << " ";
}
cout << endl;
//Perform Bubble Sort
bubbleSort(array1, ARRAY_SIZE);
//Display Second Array
cout << "Second Array (before selection sort): ";
for (int i = 0; i < ARRAY_SIZE; i++) {
cout << array2[i] << " ";
}
cout << endl;
//Perform Selection Sort
selectionSort(array2, ARRAY_SIZE);
//Separator and Output Section
cout << "-------------------------------------------------------" << endl;
cout << "OUTPUT:" << endl;
//Output Final Sorted Arrays
cout << "Final Bubble Sorted Array: ";
for (int i = 0; i < ARRAY_SIZE; i++) {
cout << array1[i] << " ";
}
cout << endl;
cout << "Final Selection Sorted Array: ";
for (int i = 0; i < ARRAY_SIZE; i++) {
cout << array2[i] << " ";
}
cout << endl;
} //end of main()