int main(int argc, char * * argv) { if(argc != 3) { printUsage(argv[0]); if(argc == 2 && strcmp("--help", argv[1]) == 0) return EXIT_SUCCESS; return EXIT_FAILURE; } int ret = EXIT_SUCCESS; // until otherwise noted const char * cmd = argv[1]; int * array = NULL; int len = 0; int i; // Read array if integers (if applicable) if(strcmp(cmd, "sort") == 0 || strcmp(cmd, "sortable") == 0) { const char * arrstr = argv[2]; if(!checkArrayStr(arrstr)) { fprintf(stderr, "Invalid array, aborting\n"); return EXIT_FAILURE; } len = strlen(arrstr); array = malloc(sizeof(int) * len); for(i = 0; i < len; ++i) array[i] = arrstr[i] - '0'; } if(strcmp(cmd, "sort") == 0) { // -- Sort command stackSort(array, len); for(i = 0; i < len; ++i) printf("%d", array[i]); printf("\n"); } else if(strcmp(cmd, "sortable") == 0) { // -- Sortable command if(isStackSortable(array, len)) printf("Y\n"); else printf("N\n"); } else if(strcmp(cmd, "shapes") == 0) { // -- Shapes command len = strtol(argv[2], NULL, 10); if(len < 1 || len > 9) { fprintf(stderr, "Invalid number of shapes... aborting\n"); ret = EXIT_FAILURE; } else { genShapes(len); } } else { // -- An error fprintf(stderr, "Invalid command: '%s', aborting\n", cmd); } free(array); return ret; }
int main(int, char**) { srand(time(NULL)); const int SIZE = 20; Stack<double> s, sorted; for(int i=0; i<SIZE; i++) { s.push(std::unique_ptr<double>( new double(rand() / double(RAND_MAX)))); } stackSort(SIZE, s, sorted); std::cout << sorted << std::endl; return 0; }
void stackSort(int n, Stack<T>& source, Stack<T>& dest, bool isMax=true) { if(n > 0) { if(isMax) leaveMinInSource(n, source, dest); else leaveMaxInSource(n, source, dest); stackSort(n-1, dest, source, !isMax); } else { Stack<T> *mySource(nullptr), *myDest(nullptr); if(!isMax) { mySource = &dest; myDest = &source; } else { mySource = &source; myDest = &dest; } while(!mySource->isEmpty()) { myDest->push(std::unique_ptr<T>(std::move(mySource->popPtr()))); } } };