Advertisement
cyter

insertion_sort

Mar 19th, 2018
454
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.81 KB | None | 0 0
  1. #include <iostream>
  2. #include <cstdlib>
  3. using std::cout;
  4.  
  5.  
  6. // CLRS exercise 2.1-2
  7.  
  8. //Template, sorts in nondecreasing order for anything where ">" and "<" are defined
  9. template<class T>
  10. T* insertion_sort1(T array[], int size)
  11. {
  12.     int j = 1,i;
  13.     T key;
  14.     while(j < size)
  15.     {
  16.         key = array[j];
  17.         i = j - 1;
  18.         while(i >= 0 && array[i] > key)
  19.         {
  20.             array[i+1] = array[i];
  21.             array[i] = key;
  22.             i--;            
  23.         } j++;
  24.     } return array;
  25. }
  26. // Sorts in nonincreasing order for anything where ">" and "<" are defined
  27. template<class T>
  28. T* insertion_sort2(T array[], int size)
  29. {
  30.     int j = 1,i;
  31.     T key;
  32.     while(j < size)
  33.     {
  34.         key = array[j];
  35.         i = j - 1;
  36.         while(i >= 0 && array[i] < key)
  37.         {
  38.             array[i+1] = array[i];
  39.             array[i] = key;
  40.             i--;            
  41.         } j++;
  42.     } return array;
  43. }
  44. template<class T>
  45. void print(T array[], int size)
  46. {
  47.     int i = 0; size--;
  48.     cout<<"{";
  49.     while(i < size)
  50.         cout<< array[i++] <<",";
  51.     cout<<array[i]<<"}";
  52. }
  53. int main(int argc, char* argv[])
  54. {
  55.     int length = argc-1;
  56.     if(length == 0)
  57.     {
  58.         cout<<"Enter elements of the array to be sorted via the CLI thus: ";
  59.         cout<<"\"./sorting 31 4 59 26 41 58\"\n";
  60.         return 0;
  61.     }
  62.     int a[length];
  63.     float b[length];    
  64.     int i = 0;
  65.    
  66.     while(i < length)
  67.     {
  68.         a[i] = atoi(argv[i+1]);
  69.         b[i] = atof(argv[i+1]);
  70.         i++;
  71.     }
  72.    
  73.     cout<<"Sorting array: "; print(b,length);
  74.     cout<<"\n";
  75.  
  76.     cout<<"(increasing order) --> ";
  77.     print(insertion_sort1(b, length),length);
  78.     cout<<"\n";
  79.  
  80.     cout<<"(decreasing order) --> ";
  81.     print(insertion_sort2(b, length),length);
  82.     cout<<"\n";
  83.  
  84.     return 0;
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement