m2skills

selection cpp

Apr 7th, 2017
852
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.46 KB | None | 0 0
  1. /*program to perform selection sort on an array*/
  2. #include <iostream>
  3. #include<vector>
  4. #include<sstream>
  5.  
  6. using namespace std;
  7.  
  8. // method that sorts the vector using selection sort
  9. vector<int> selectionSort(vector<int> numbers){
  10.     int temp;
  11.    
  12.     // loop i from 0 to n-1
  13.     // assign minimum element Index as i initially
  14.     for(int i=0; i<numbers.size()-1; i++){
  15.         int minIndex = i;
  16.        
  17.         // loop j from i+1 to n
  18.         // compare jth element to minIndex element
  19.         for(int j=i+1; j< numbers.size(); j++){
  20.            
  21.             if(numbers[minIndex] > numbers[j]){
  22.                 minIndex = j;
  23.             }
  24.         }
  25.        
  26.         // swap the smallest element to the minIndex position
  27.         int temp = numbers[minIndex];
  28.         numbers[minIndex] = numbers[i];
  29.         numbers[i] = temp;
  30.     }
  31.     // return sorted vector
  32.     return numbers;
  33. }
  34.  
  35. int main()
  36. {
  37.  
  38.     int n;
  39.     string str;
  40.     vector<int> ints;
  41.  
  42.     cout<<"Enter the array to be sorted : ";
  43.     cin>>str;
  44.  
  45.     // removing ","  and replacing it with spaces
  46.     // this is to convert string to a vector of integers
  47.     // you can also take input into array using the conventional way
  48.     for (string::iterator it = str.begin(); it != str.end(); ++it) {
  49.         if (*it == ',') {
  50.             *it = ' ';
  51.         }
  52.         else continue;
  53.     }
  54.  
  55.     // storing the string by extracting integers and puting them into vector
  56.     stringstream ss(str);
  57.     while(ss >> n){
  58.         ints.push_back(n);
  59.     }
  60.  
  61.     ints = selectionSort(ints);
  62.  
  63.     cout<<"\nThe Array after sorting is : ";
  64.     for(int i=0; i<ints.size(); i++){
  65.         cout<<ints[i]<<" ";
  66.     }
  67. }
Add Comment
Please, Sign In to add comment