Skip to content

Instantly share code, notes, and snippets.

@MatMercer
Created January 16, 2021 23:07
Show Gist options
  • Save MatMercer/b355d3e528ec0f71a812cecc19f56269 to your computer and use it in GitHub Desktop.
Save MatMercer/b355d3e528ec0f71a812cecc19f56269 to your computer and use it in GitHub Desktop.
Sort algorithms with struct templates in C++
#include <iostream>
#include <vector>
#include "sortalgs.h"
int main(int argc, char **argv) {
std::vector<int> v = {1, 5, 2, 3, -3, -2, -1, 0, 3, 1};
sortalg<Bubble>::sort(v.begin(), v.end());
auto start = v.begin();
auto end = v.end();
for (auto ptr = start; ptr < end; ptr++) {
std::cerr << *ptr << std::endl;
}
return 0;
}
#ifndef ALGORITHMS_H
#define ALGORITHMS_H
#include <algorithm>
template<typename SortType>
struct sortalg {
template<class RandomAccessIterator>
static void sort(RandomAccessIterator start, RandomAccessIterator end);
};
class Bubble;
template<>
template<class RandomAccessIterator>
void sortalg<Bubble>::sort(RandomAccessIterator start, RandomAccessIterator);
template<>
template<class RandomAccessIterator>
void sortalg<Bubble>::sort(RandomAccessIterator start, RandomAccessIterator end) {
int j = 1;
for (auto current = start; current < end; current++, j++) {
for(auto bubble = start; bubble < end - j; bubble++) {
auto next = bubble + 1;
if (*bubble > *next) {
std::swap(*bubble, *next);
}
}
}
}
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment