1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
|
#ifndef __SORTING_HELPER_H
#define __SORTING_HELPER_H
#include <iostream>
using namespace std;
//Functions for allocating various integer arrays of length n
int* increasingArray(int n);
int* decreasingArray(int n);
int* zeroArray(int n);
int* randomArray(int n);
/**
Returns whether an array is in sorted order
Note: the values in the array must be comparable with <; compilation will fail otherwise.
@param arr the array to test
@param n the length of the array
@return whether the array is sorted
*/
template <class T> bool isSorted(T* arr, int n)
{
for (int i = 0; i < n - 1; i++)
if (arr[i + 1] < arr[i])
return false;
return true;
}
/**
Prints an array of size n, with spaces in between and a newline at the end
@param arr the array to print
@param n the length of the array
*/
template <class T> void printArray(T* arr, int n)
{
for (int i = 0; i < n; i++)
cout << arr[i] << ' ';
cout << endl;
}
/**
Compares 3 values and returns which is the median
When two values are equal, one of the two will be indicated
Note: these values must be comparable with <; compilation will fail otherwise.
@param a,b,c 3 values
@return 1, 2, or 3, depending on whether a, b, or c is the median
*/
template <class T> int medianof3(T a, T b, T c)
{
if (a < c)
{
if (b < a)
return 1;
else if (c < b)
return 3;
else
return 2;
}
else if (b < c)
return 3;
else if (a < b)
return 1;
else
return 2;
}
/**
Swaps two values
Name capitalized to avoid potential naming conflicts
@param a,b values to swap
*/
template <class T> void Swap(T& a, T& b)
{
T t = a;
a = b;
b = t;
}
#endif
|