Sort in reverse order. "Don't repeat yourself" rule
c++, dry, reverse, sorting, ternary-operator
Solution
You could add a comparator as a type, like the example below:
template<template<class> class COMP = std::less, typename T>
void insertionSort(T* elements, int size) {
T tempElement;
int j;
COMP<T> pred;
for (int i = 0; i < size; ++i) {
tempElement = elements[i];
for (j = i - 1; j >= 0 && pred(tempElement, elements[j]); --j)
elements[j + 1] = elements[j];
elements[j + 1] = tempElement;
}
}
LIVE DEMO
Problem
Here is a piece of C++ code that do an Insertion Sort: ``` #ifndef INSERTIONSORT #define INSERTIONSORT template<class T> void insertionSort(T* elements, int size, int reverse = 0) { T tempElement; int j; for (int i = 0; i < size; ++i) { tempElement = elements[i]; for (j = i - 1; j >= 0 && elements[j] > tempElement; j--) elements[j + 1] = elements[j]; elements[j + 1] = tempElement; } } #endif ``` I can't write it without repeating code. Its not the first time I face that kind of problem. All I need is to replace `<` to `>`, when `reverse` = 1. The first way that I tried is to use ternary operator: `(repeat)?(elements[j] > tempElement):(elements[j] < tempElement)` It looks little bit strange and I know its not the best way to solve the problem, so I tried this: `elements[j] (reverse)?(<):(>) tempElement` But its not correct and doesn't work. Also ternary operator doubled the number of elementary operations in if statement. I know it's just an Insertion Sort that does Θ(n^2) operations (not the best way of sorting a lot of elements), but I think there is a better way to write it. Another thing is that you can't use this: `(repeat)?(-1):(1) * (elements[j] - tempElement) > 0` Because class T can have only operator= and operator> (operator<). Also you can't call function in loop, because it will be Θ(n) or Θ(n^2) calls. Here is the last solution: ``` #ifndef INSERTIONSORT #define INSERTIONSORT template<class T> void insertionSort(T* elements, int size, int reverse = 0) { T tempElement; int j; if (reverse) for (int i = 0; i < size; ++i) { tempElement = elements[i]; for (j = i - 1; j >= 0 && elements[j] < tempElement; j--) elements[j + 1] = elements[j]; elements[j + 1] = tempElement; } else for (int i = 0; i < size; ++i) { tempElement = elements[i]; for (j = i - 1; j >= 0 && elements[j] > tempElement; j--) elements[j + 1] = elements[j]; elements[j + 1] = tempElement; } } #endif ``` The only problem is repeating code. The main principle of programming says: "Don't repeat yourself" (D.R.Y). I really don't know how to write code correctly here.