Advertisement
adnan_dipta89

InsertionSort

Oct 18th, 2019
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.89 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. vector<string> split_string(string);
  6. void print(vector<int> arr)
  7. {
  8.     for(int i = 0; i < arr.size(); i++)
  9.     {
  10.         cout << arr[i] << " ";
  11.     }
  12.     cout << endl;
  13. }
  14. void insert(int j, vector<int>& arr)
  15. {
  16.     int x = arr[j],i;
  17.     //cout << j << endl;
  18.     for(i = j-1; i >= 0; i--)
  19.     {
  20.         if(arr[i] > x)
  21.         {
  22.             arr[i+1] = arr[i];
  23.         }
  24.         else
  25.             break;
  26.     }
  27.     //cout << i << endl;
  28.     arr[i+1] = x;
  29. }
  30. // Complete the insertionSort2 function below.
  31. void insertionSort2(int n, vector<int> arr) {
  32.     for(int i = 1; i < n; i++)
  33.     {
  34.         insert(i,arr);
  35.         print(arr);
  36.     }
  37.  
  38. }
  39.  
  40. int main()
  41. {
  42.     int n;
  43.     cin >> n;
  44.     cin.ignore(numeric_limits<streamsize>::max(), '\n');
  45.  
  46.     string arr_temp_temp;
  47.     getline(cin, arr_temp_temp);
  48.  
  49.     vector<string> arr_temp = split_string(arr_temp_temp);
  50.  
  51.     vector<int> arr(n);
  52.  
  53.     for (int i = 0; i < n; i++) {
  54.         int arr_item = stoi(arr_temp[i]);
  55.  
  56.         arr[i] = arr_item;
  57.     }
  58.  
  59.     insertionSort2(n, arr);
  60.  
  61.     return 0;
  62. }
  63.  
  64. vector<string> split_string(string input_string) {
  65.     string::iterator new_end = unique(input_string.begin(), input_string.end(), [] (const char &x, const char &y) {
  66.         return x == y and x == ' ';
  67.     });
  68.  
  69.     input_string.erase(new_end, input_string.end());
  70.  
  71.     while (input_string[input_string.length() - 1] == ' ') {
  72.         input_string.pop_back();
  73.     }
  74.  
  75.     vector<string> splits;
  76.     char delimiter = ' ';
  77.  
  78.     size_t i = 0;
  79.     size_t pos = input_string.find(delimiter);
  80.  
  81.     while (pos != string::npos) {
  82.         splits.push_back(input_string.substr(i, pos - i));
  83.  
  84.         i = pos + 1;
  85.         pos = input_string.find(delimiter, i);
  86.     }
  87.  
  88.     splits.push_back(input_string.substr(i, min(pos, input_string.length()) - i + 1));
  89.  
  90.     return splits;
  91. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement