m2skills

shell cpp

Apr 4th, 2017
170
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.24 KB | None | 0 0
  1. #include <iostream>
  2. #include<vector>
  3. #include<sstream>
  4.  
  5. using namespace std;
  6. vector<int> shellSort(vector<int>);
  7. int main()
  8. {
  9.  
  10.     int n;
  11.     string str;
  12.     vector<int> ints;
  13.  
  14.     cout<<"Enter the array to be sorted : ";
  15.     cin>>str;
  16.  
  17.     for (string::iterator it = str.begin(); it != str.end(); ++it) {
  18.         if (*it == ',') {
  19.             *it = ' ';
  20.         }
  21.         else continue;
  22.     }
  23.  
  24.     stringstream ss(str);
  25.  
  26.     while(ss >> n){
  27.         ints.push_back(n);
  28.     }
  29.  
  30.     ints = shellSort(ints);
  31.     cout<<"\nThe Array after sorting is : ";
  32.     for(int i=0; i<ints.size(); i++){
  33.         cout<<ints[i]<<" ";
  34.     }
  35. }
  36.  
  37. vector<int> shellSort(vector<int> numbers){
  38.         int gap = numbers.size() / 2;
  39.        
  40.         while (gap > 0){
  41.             // loop till i is in range from gaps to lenght of the list
  42.             for (int i = 0; i < numbers.size(); i++){
  43.                 // store the ith element in the temp variable
  44.                 int temp = numbers[i];
  45.                 int j = i;
  46.                 // applying insertion sort on the sublist
  47.                 // shifting the elements larger than the ith element to the right
  48.                 while(j >= gap && numbers[j - gap] > temp){
  49.                     numbers[j] = numbers[j - gap];
  50.                     j -= gap;
  51.                 }  
  52.                 // puting the element at its correct position  
  53.                 numbers[j] = temp;
  54.             }  
  55.             // reduce gap by it half   
  56.             gap = gap/2;
  57.         }  
  58.         return numbers;
  59.     }
Add Comment
Please, Sign In to add comment