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 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
|
//Michaela Ervin - Sorting functions
#ifndef H_SORTFUNCS
#define H_SORTFUNCS
template <class dType>
void swapitem(dType& one, dType& two)
{
dType d;
d = one;
one = two;
two = d;
}
//Works with Arrays and Vectors
template <class dType>
void bubblesort(dType &temp, int n)
{
bool sorted = false;
int i = 0, j = 1;
while (!sorted)
{
sorted = true;
for (i = 0; i < n - j; i++)
{
if (temp[i] > temp[i + 1])
{
swapitem(temp[i], temp[i + 1]);
sorted = false;
}
}
j++;
}
}
//Works with Arrays and Vectors
template <class dType>
void selectsort(dType &temp, int n)
{
int j = 0, k = 0, small;
if (n > 1)
for (k = 0; k < n - 1; k++)
{
small = k;
for (j = k + 1; j < n; j++)
if (temp[j] < temp[small]) small = j;
if (k != small) swapitem(temp[k], temp[small]);
}
}
//Works with Arrays - Change datatype of save to work with vectors
//Array must have one open slot on the end
template <class dType>
void insertionsort(dType &temp, int n)
{
int j = 0, k = 0;
dType save;
for (k = n - 1; k >= 0; k--)
{
j = k + 1;
save = temp[k];
temp[n] = save;
while (save > temp[j])
{
temp[j - 1] = temp[j];
j++;
}
temp[j - 1] = save;
}
}
//Works with Arrays and Vectors
template <class dType>
void quicksort(dType &temp, int left, int right) {
int i = left, j = right;
int pivot = temp[(left + right) / 2];
while (i <= j)
{
while (temp[i] < pivot)i++;
while (temp[j] > pivot)j--;
if (i <= j)
{
swapitem(temp[i], temp[j]);
i++;
j--;
}
}
if (left < j)quicksort(temp, left, j);
if (i < right)quicksort(temp, i, right);
}
//Works with Arrays and Vectors
template <class dType>
void shellsort(dType &temp, int n)
{
bool swap = false;
int i, gap;
gap = n;
while (gap >= 1)
{
if (swap == false)
gap = gap / 2;
swap = false;
for (i = 0; i < (n - gap); i++)
{
if (temp[i] > temp[i + gap])
{
swapitem(temp[i], temp[i + gap]);
swap = true;
}
}
}
}
#endif
|