//Cameron Pham CS1A Chapter 8, p. 489, #10
//
/******************************************************************************
* SORT ORDER
* ______________________________________________________________________________
* This program demonstrates two sorting methods, bubble sort and selection sort,
* using two identical arrays of eight integers. It displays the original
* contents of each array, sorts the values, and displays the array after each
* pass. The program allows the user to observe and compare how each sorting
* method organizes the numbers.
*******************************************************************************/
#include <iostream>
using namespace std;
// Function prototypes
void displayArray(const int array[], int size);
void bubbleSort(int array[], int size);
void selectionSort(int array[], int size);
int main()
{
const int SIZE = 8;
// Store identical values in both arrays
int firstArray[SIZE] = {8, 3, 6, 1, 7, 2, 5, 4};
int secondArray[SIZE] = {8, 3, 6, 1, 7, 2, 5, 4};
// Display and sort the first array using bubble sort
cout << "BUBBLE SORT" << endl;
cout << "Original array: ";
displayArray(firstArray, SIZE);
bubbleSort(firstArray, SIZE);
// Display and sort the second array using selection sort
cout << "\nSELECTION SORT" << endl;
cout << "Original array: ";
displayArray(secondArray, SIZE);
selectionSort(secondArray, SIZE);
return 0;
}
// Display all values in an array
void displayArray(const int array[], int size)
{
for (int count = 0; count < size; count++)
{
cout << array[count] << " ";
}
cout << endl;
}
// Sort the array using ascending bubble sort
void bubbleSort(int array[], int size)
{
int temp;
for (int pass = 0; pass < size - 1; pass++)
{
// Compare neighboring values and swap when needed
for (int count = 0; count < size - pass - 1; count++)
{
if (array[count] > array[count + 1])
{
temp = array[count];
array[count] = array[count + 1];
array[count + 1] = temp;
}
}
// Display the array after each pass
cout << "Pass " << pass + 1 << ": ";
displayArray(array, size);
}
}
// Sort the array using ascending selection sort
void selectionSort(int array[], int size)
{
int minIndex;
int temp;
for (int start = 0; start < size - 1; start++)
{
minIndex = start;
// Find the smallest value in the unsorted portion
for (int count = start + 1; count < size; count++)
{
if (array[count] < array[minIndex])
{
minIndex = count;
}
}
// Move the smallest value into its correct position
temp = array[start];
array[start] = array[minIndex];
array[minIndex] = temp;
// Display the array after each pass
cout << "Pass " << start + 1 << ": ";
displayArray(array, size);
}
}