The program is separated in main.cpp, quicksort.cpp, partition.cpp and swap.cpp. There is also a header file to each .cpp file. The idea is from this site.
As you can see, I tried to be very modular. I think instead of having swap.cpp I could've simply used std::swap, right?
But the more important thing is, that I'd like to know how I can improve this quicksort algorithm or how to improve my program in general (not only the algorithm itself).
My three .hpp files are looking like this:
#ifndef __qs__name__
#define __qs__name__
#include <vector>
//protype
#endif
partition.cpp:
#include "partition.hpp"
#include "swap.hpp"
int partition(std::vector<int>& v, int ileft, int iright, int ipivot)
{
int i = ileft, j = iright;
while (i <= j)
{
while (v[i] < ipivot)
i++;
while (v[j] > ipivot)
j--;
if (i <= j)
{
swap(v, i, j);
i++;
j--;
}
}
return j;
}
quicksort.cpp:
#include "quicksort.hpp"
#include "partition.hpp"
void quicksort(std::vector<int>& v, int ileft, int iright)
{
int p, ipivot = v[iright]; // v[(ileft + iright) / 2];
p = partition(v, ileft, iright, ipivot);
if(ileft < p)
quicksort(v, ileft, p);
if((p + 1) < iright)
quicksort(v, p + 1, iright);
}
swap.cpp:
#include "swap.hpp"
void swap(std::vector<int>& v, int i, int j)
{
int temp = v[i];
v[i] = v[j];
v[j] = temp;
}
main.cpp:
#include <vector>
#include "partition.hpp"
#include "quicksort.hpp"
#include "swap.hpp"
int main()
{
std::vector<int> v;
v.push_back(7);
v.push_back(10);
v.push_back(11);
v.push_back(1);
/*v.push_back(-4543);
v.push_back(88);
v.push_back(5);
v.push_back(3);
v.push_back(31);
v.push_back(34);
v.push_back(7);*/
for (int i = 0; i < v.size(); i++)
std::cout << v[i] << std::endl;
quicksort(v, 0, v.size()-1);
std::cout << "\n";
for (int i = 0; i < v.size(); i++)
std::cout << v[i] << std::endl;
return 0;
}