Advertisement
tombroskipc

shell_ex

Jul 17th, 2021
150
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.84 KB | None | 0 0
  1. %%writefile ShellSortEx.h
  2.  
  3. #ifndef SHELLSORTEX_H
  4. #define SHELLSORTEX_H
  5. #include "ISortEx.h"
  6.  
  7. template<class T>
  8. class ShellSortEx: public ISortEx<T>{
  9. private:
  10.     int *num_segment_list;
  11.     int num_phases;
  12.    
  13. public:
  14.     ShellSortEx(int *num_segment, int num_phases){
  15.         this->num_phases = num_phases;
  16.         this->num_segment_list = new int[num_phases];
  17.         for(int idx=0; idx < num_phases; idx++)
  18.             this->num_segment_list[idx] = num_segment[idx];
  19.     }
  20.     ~ShellSortEx(){
  21.         delete []num_segment_list;
  22.     }
  23.    
  24.     void sortSegment(T array[], int size,
  25.             int segment_idx, int cur_segment_total,
  26.             int (*comparator)(T&, T&))
  27.     {
  28.         //YOUR CODE HERE
  29.         int current;
  30.         int walker;
  31.         T temp;
  32.         current = segment_idx + cur_segment_total;
  33.             while(current < size)
  34.         {
  35.             temp = array[current];
  36.             walker = current - cur_segment_total;
  37.             while((walker >= 0) && comparator(temp, array[walker]) < 0)
  38.             {
  39.                 array[walker + cur_segment_total] = array[walker];
  40.                 walker -= cur_segment_total;
  41.             }
  42.             array[walker + cur_segment_total] = temp;
  43.             current += cur_segment_total;
  44.         }
  45.  
  46.     }
  47.     /*
  48.     shell_sort
  49.     -----------
  50.     num_segments:
  51.          + The first must be 1, for examples: [1,3,7]
  52.     */
  53.  
  54.  
  55.     void sort(T array[], int size, int (*comparator)(T&,T&), int stride=1)
  56.     {
  57.         //YOUR CODE HERE
  58.         for(int k = num_phases - 1; k >= 0; k--)
  59.         {
  60.             int numOfSeg = num_segment_list[k];
  61.             for(int segment_idx = 0; segment_idx < numOfSeg; segment_idx++)
  62.                 sortSegment(array, size, segment_idx * stride, numOfSeg * stride, comparator);
  63.         }
  64.     }
  65. };
  66.  
  67. #endif /* SHELLSORTEX_H */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement