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 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
|
/*====================================================
Projekt : Sort Algorithm
Codename : Pharao (of its pyramide formation)
Programmer: Necip 07.07.2016
====================================================
Description
===========
Given an array of n integers: 9 8 7 6 5 4 3 2 1 0
Compare pairs starting with index 0, step 2
9 8 7 6 5 4 3 2 1 0
8 9 6 7 4 5 2 3 0 1
Compare pairs starting with index 1
8 9 6 7 4 5 2 3 0 1
6 9 4 7 2 5 0 3
Compare pairs starting with index 2
6 9 4 7 2 5 0 3
4 9 2 7 0 5
and so on.
Then start again comparision with index 0.
Sorting is finished if no swaping occured.
This is the hole cyles of comparisons of this example:
9 8 7 6 5 4 3 2 1 0
8 9 6 7 4 5 2 3 0 1
6 9 4 7 2 5 0 3
4 9 2 7 0 5
2 9 0 7
0 9
new cyle
8 6 4 2 0 9 7 5 3 1
6 8 2 4 0 9 5 7 1 3
2 8 0 4 5 9 1 7
0 8 5 4 1 9
5 8 1 4
1 8
new cyle
6 2 0 5 1 8 4 9 7 3
2 6 0 5 1 8 4 9 3 7
0 6 1 5 4 8 3 9
1 6 4 5 3 8
4 6 3 5
3 6
new cyle
2 0 1 4 3 6 5 8 9 7
0 2 1 4 3 6 5 8 7 9
1 2 3 4 5 6 7 8
2 3 4 5 6 7 finished
result
0 1 2 3 4 5 6 7 8 9
====================================================
History log
07.07.2016 - First concept
====================================================*/
#include <iostream>
#include <string>
/*
* Sort algorithm, recursive
*/
void sort(
int* aValues,
int iCount,
int iCurrentStartIndex,
int iCurrentEndIndex) {
if (iCurrentStartIndex >= iCurrentEndIndex) {
// Start next cyle
sort (aValues, iCount, 0, iCount-1);
return;
}
bool boSwap = false;
for (int i=iCurrentStartIndex;i<=iCurrentEndIndex;i+=2) {
if (aValues[i] > aValues[i+1]) {
int iValueTmp = aValues[i];
aValues[i ] = aValues[i+1];
aValues[i+1] = iValueTmp;
boSwap = true;
}
}
if (!boSwap)
return;
// sort next level
sort (aValues, iCount, iCurrentStartIndex +1, iCurrentEndIndex -1);
}
/*
* dump array content
*/
void dump(int* aValues, int iCount) {
for (int i=0;i<iCount;i++)
std::cout << aValues[i];
std::cout << std::endl;
}
/*
* MAIN
*/
int main(void) {
int MAX = 10;
int aValues[MAX] = {9,8,7,6,5,4,3,2,1,0};
dump (aValues, MAX);
sort (aValues, MAX, 0, MAX-1);
dump (aValues, MAX);
return 0;
}
|