I have developed the Insertion Sort and Quicksort algorithms in C++. Now, I intend to create at least four variations of the Quicksort algorithm. They will vary in how they choose pivot and whether they use insertion sort for small lists or not. In Java or C#, to avoid code duplication and conflicting names, I would implement each version of the Quicksort algorithm in a separate class file and use inheritance. Specifically, I would create the following classes:
QuicksortFixedPivot
QuicksortRandomPivot
QuicksortFixedPivotInsertion
- subarrays with at mostk
elements are sorted using insertion sortQuicksortRandomPivotInsertion
However, from my understanding "standalone" algorithms like Quicksort are usually not implemented in classes in C++.
Below is my initial implementation of Quicksort.
quicksort.hpp
#pragma once
#include <vector>
namespace algorithms
{
void quicksort(std::vector<int> &list);
void quicksort(std::vector<int> &list, int left, int right);
int partition(std::vector<int> &list, int left, int right);
}
quicksort.cpp
#include "quicksort.hpp"
namespace alg = algorithms;
void alg::quicksort(std::vector<int> &list)
{
alg::quicksort(list, 0, list.size() - 1);
}
void alg::quicksort(std::vector<int> &list, int left, int right)
{
if (left >= right)
return;
int oldPivot = alg::partition(list, left, right);
alg::quicksort(list, left, oldPivot - 1);
alg::quicksort(list, oldPivot + 1, right);
}
int alg::partition(std::vector<int> &list, int left, int right)
{
int pivot = list[left + (right-left)/2];
while (true)
{
while (list[left] < pivot)
left++;
while (list[right] > pivot)
right--;
if (left >= right)
return left;
std::swap(list[left], list[right]);
}
}
With the above background in mind, I have two questions.
Firstly, for being a single Quicksort implementation, have I used header files appropriately and structured my code in a good way? For example, is it good that the algorithm is outside of a class?
Secondly, how should I approach creating different versions of this algorithm while avoiding code duplication and naming conflicts? For instance, should I use classes or some other language construct?
I would appreciate if the answer included minimal code snippets that elucidate how any relevent language constructs should be used to achieve neat code.