Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <cstdlib>
- using std::cout;
- // CLRS exercise 2.1-2
- //Template, sorts in nondecreasing order for anything where ">" and "<" are defined
- template<class T>
- T* insertion_sort1(T array[], int size)
- {
- int j = 1,i;
- T key;
- while(j < size)
- {
- key = array[j];
- i = j - 1;
- while(i >= 0 && array[i] > key)
- {
- array[i+1] = array[i];
- array[i] = key;
- i--;
- } j++;
- } return array;
- }
- // Sorts in nonincreasing order for anything where ">" and "<" are defined
- template<class T>
- T* insertion_sort2(T array[], int size)
- {
- int j = 1,i;
- T key;
- while(j < size)
- {
- key = array[j];
- i = j - 1;
- while(i >= 0 && array[i] < key)
- {
- array[i+1] = array[i];
- array[i] = key;
- i--;
- } j++;
- } return array;
- }
- template<class T>
- void print(T array[], int size)
- {
- int i = 0; size--;
- cout<<"{";
- while(i < size)
- cout<< array[i++] <<",";
- cout<<array[i]<<"}";
- }
- int main(int argc, char* argv[])
- {
- int length = argc-1;
- if(length == 0)
- {
- cout<<"Enter elements of the array to be sorted via the CLI thus: ";
- cout<<"\"./sorting 31 4 59 26 41 58\"\n";
- return 0;
- }
- int a[length];
- float b[length];
- int i = 0;
- while(i < length)
- {
- a[i] = atoi(argv[i+1]);
- b[i] = atof(argv[i+1]);
- i++;
- }
- cout<<"Sorting array: "; print(b,length);
- cout<<"\n";
- cout<<"(increasing order) --> ";
- print(insertion_sort1(b, length),length);
- cout<<"\n";
- cout<<"(decreasing order) --> ";
- print(insertion_sort2(b, length),length);
- cout<<"\n";
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement