I created a program that measures the time for the bubble sort algorithm to sort a list of numbers:
#include <iostream>
#include <fstream>
#include <vector>
#include <time.h>
std::vector<int> FiletoVector()
{
std::ifstream SortFile("Number_Sort.input");
std::vector<int> vector;
int read;
while(SortFile >> read)
{
vector.push_back(read);
}
return vector;
}
void PrintTime(std::string sorttype, std::vector<int> funcinput(std::vector<int>), std::vector<int> vecinput)
{
//Start Time
float time = clock();
funcinput(vecinput);
//End Time
time = (clock() - time) / CLOCKS_PER_SEC;
std::cout << sorttype << " took " << time << " seconds!" << std::endl;
}
std::vector<int> BubbleSort(std::vector<int> vecinput)
{
for(int i = 0; i < vecinput.size(); i++)
{
for(int n = 0; n < vecinput.size(); n++)
{
//std::cout << vecinput[n] << " " << vecinput[n + 1] << std::endl;
if(vecinput[n] > vecinput[n + 1])
{
int a = vecinput[n];
int b = vecinput[n + 1];
vecinput[n] = b;
vecinput[n + 1] = a;
}
}
}
return vecinput;
}
int main()
{
std::vector<int> nums = FiletoVector();
//REMEMBER FUNCTION IN PARAMETER HAS NO ()
PrintTime("Bubble Sort", BubbleSort, nums);
/*
//Print Ordered List and Time (Bubble)
for(int i = 0; i < vecBubble.size(); i++)
{
std::cout << vecBubble[i] << std::endl;
}
std::cout << time << " seconds!" << std::endl;
*/
}
As you can see the first function is to take the file (Number_Sort.input
) and make it into a vector (since it can change size in elements). Then my second function is prints out the time it takes for the sorting algorithm to sort all of its data. Finally my last function is the bubble sort algorithm.
The reason I put my code in this fashion is that so I can later on learn other algorithms and put them in here, and then compare the speed that they execute them with different data sets.
But my code feels a bit messy, I feel like I can further make it more readable, specifically the PrintTime
function and all of those parameters. I am not even sure if I did the funcinput(std::vector<int>)
in a proper way. I had to make the input of the bubble sort function as a separator parameter (I could not do PrintTime("Bubble Sort", BubbleSort(nums))
. And all of that std::vector<int>
is gonna kill me! Is there any way to clean that mess too?