1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
|
#include <iostream>
#include <utility>
#include "keep_window_open.h"
void bubbleSort(int array[], const int size);
void displaySortedArray(const int array[], const int size);
int main()
{
using namespace std;
const int size{ 9 };
int array[size] = { 6, 3, 2, 9, 7, 1, 5, 4, 8 };
bubbleSort(array, size);
displaySortedArray(array, size);
keep_window_open();
return 0;
}
void bubbleSort(int array[], const int size)
{
using namespace std;
for (int iteration = 0; iteration < size; ++iteration)
{
bool swapped{ false };
for (int currentIndex = 0; currentIndex < size - 1; ++currentIndex)
{
if (array[currentIndex] > array[currentIndex + 1])
{
swap(array[currentIndex], array[currentIndex + 1]);
swapped = true;
}
if (array[currentIndex] < array[currentIndex + 1])
{
continue;
}
}
if (!swapped)
{
cout << "Early termination on iteration: " << iteration + 1 << "\n";
}
}
}
void displaySortedArray(const int array[], const int size)
{
using namespace std;
for (int index = 0; index < size; ++index)
{
cout << array[index] << " ";
}
cout << "\n";
}
|