Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*program to perform selection sort on an array*/
- #include <iostream>
- #include<vector>
- #include<sstream>
- using namespace std;
- // method that sorts the vector using selection sort
- vector<int> selectionSort(vector<int> numbers){
- int temp;
- // loop i from 0 to n-1
- // assign minimum element Index as i initially
- for(int i=0; i<numbers.size()-1; i++){
- int minIndex = i;
- // loop j from i+1 to n
- // compare jth element to minIndex element
- for(int j=i+1; j< numbers.size(); j++){
- if(numbers[minIndex] > numbers[j]){
- minIndex = j;
- }
- }
- // swap the smallest element to the minIndex position
- int temp = numbers[minIndex];
- numbers[minIndex] = numbers[i];
- numbers[i] = temp;
- }
- // return sorted vector
- return numbers;
- }
- int main()
- {
- int n;
- string str;
- vector<int> ints;
- cout<<"Enter the array to be sorted : ";
- cin>>str;
- // removing "," and replacing it with spaces
- // this is to convert string to a vector of integers
- // you can also take input into array using the conventional way
- for (string::iterator it = str.begin(); it != str.end(); ++it) {
- if (*it == ',') {
- *it = ' ';
- }
- else continue;
- }
- // storing the string by extracting integers and puting them into vector
- stringstream ss(str);
- while(ss >> n){
- ints.push_back(n);
- }
- ints = selectionSort(ints);
- cout<<"\nThe Array after sorting is : ";
- for(int i=0; i<ints.size(); i++){
- cout<<ints[i]<<" ";
- }
- }
Add Comment
Please, Sign In to add comment