Skip to content

Instantly share code, notes, and snippets.

@waqaraqeel
Last active August 29, 2015 14:07
Show Gist options
  • Save waqaraqeel/24a39c03d78f99ee1e54 to your computer and use it in GitHub Desktop.
Save waqaraqeel/24a39c03d78f99ee1e54 to your computer and use it in GitHub Desktop.
Recursive function for detecting sorting type of passed array
#include <iostream>
using namespace std;
const int ASC = 0;
const int DESC = 1;
const int NOORDR = 2;
const int EQELEM = 3;
const int ARRAYEND = 4;
void test();
int main()
{
test();
}
int sortType(int array[], int begin, int end)
{
if(begin+2 > end)
return ARRAYEND;
int next = sortType(array, begin+1, end);
switch(next)
{
case ASC:
return (array[begin] <= array[begin+1]) ? ASC : NOORDR;
case DESC:
return (array[begin] >= array[begin+1]) ? DESC : NOORDR;
case EQELEM:
case ARRAYEND:
if(array[begin] < array[begin+1])
return ASC;
if(array[begin] > array[begin+1])
return DESC;
return EQELEM;
default:
return NOORDR;
}
}
void test()
{
int value;
int eqarr[] = {1, 1, 1, 1, 1, 1, 1};
int asarr[] = {1, 1, 2, 2, 3, 3, 3};
int dsarr[] = {3, 3, 2, 2, 2, 2, 1};
int noarr[] = {1, 2, 3, 1, 1, 1, 1};
int nnarr[] = {1};
value = sortType(eqarr ,0, 7);
if (value!=EQELEM)
cout << ("EQELEM failed");
value = sortType(asarr ,0, 7);
if (value!=ASC)
cout << ("ASC failed");
value = sortType(dsarr ,0, 7);
if (value!=DESC)
cout << ("DESC failed");
value = sortType(noarr ,0, 7);
if (value!=NOORDR)
cout << ("NOORDR failed");
value = sortType(nnarr, 0, 1);
if (value!=ARRAYEND)
cout << ("ARRAYEND failed");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment