*More fully fledged applications can be found on the Products page. The Bash page is dedicated to fully commented oneliners, and a MySQL quick reference is available here.
/*
Will Bergen
bubble_sort.cpp
Implementation of Bubble sort on a randomly filled vector, timed with high res clock
chrono is from C++11, so compile with -std=gnu++11
*/
#include <iostream>
#include <vector>
#include <chrono>
using namespace std;
using namespace std::chrono;
void pretty_print(vector<int> array);
void swap(int &in1, int &in2);
void rand_fill();
void bubble_sort();
int aSize = 500; // Size of array to sort
vector<int> a; // Array to sort
int main() {
// Randomly Fill Array:
rand_fill();
// Print Array before sorting:
// pretty_print(a);
// Time and Execute Sort:
high_resolution_clock::time_point t1 = high_resolution_clock::now();
bubble_sort();
high_resolution_clock::time_point t2 = high_resolution_clock::now();
// Print Time:
cout << "Operation Finished in " << duration_cast<microseconds>(t2-t1).count()*.000001 << " Seconds." << endl;
// Print Array after sorting:
// pretty_print(a);
}
void swap(int &in1, int &in2) {
int temp = in1;
in1 = in2;
in2 = temp;
}
void rand_fill() {
srand(time(NULL)); // Seed once
for (int i = 0; i<aSize; i++){
a.push_back((rand() % 100)+1); // nums 1-100
}
}
void bubble_sort() {
cout << "Running Bubble Sort..." << endl;
bool swapped;
double num_swaps = 0;
do
{
swapped = false;
for (int i = 1; i < aSize; ++i)
{
if (a[i-1] > a[i]) {
swap(a[i-1], a[i]);
num_swaps++;
swapped = true;
}
}
} while (swapped);
cout << "Bubble Sort Swaps: " << num_swaps << endl;
}
void pretty_print(vector<int> array) {
for (int i = 0; i < array.size()-1; ++i)
{
cout << array[i] << ",";
}
cout << array[array.size()-1] << endl;
}