Quantcast
Channel: Braden the Software Guy » Sorting and Searching
Viewing all articles
Browse latest Browse all 4

C++ – Selection Sort

$
0
0

Daily Program for 4/28/2013

Animation of a selection sort created with Mat...

Source – Wikipedia

Today we will continue implementing sorting algorithms, but will skip the exchange sorts like bubble sort, cocktail sort, gnome sort, and odd-even sort and will implement our first selection sort in C++. The selection sort works by finding the minimum element in the data structure and pushing it to the beginning of the data structure. We then find the minimum element in the data structure minus the minimum which has been swapped to the zeroth plus the number of swaps so far position. We continue on in this fashion until we reach the final element and are able to break the loop. The selection sort algorithm always has a runtime of O(n^2) which makes it less useful for large vectors and arrays. It does ensure a constant O(n^2) for small to mid-size vectors and arrays, which is beneficial if the elements are mostly out of order.

Problem Statement for the Selection Sort Algorithm:

Take an arbitrary amount of integers from the user and add them to a vector. Print out a string representation of the vector and then sort the vector using the selection sort algorithm. Print out the sorted vector and exit the program.

Code:

#include <iostream>
#include <vector>
#include <algorithm>
#include <string>

template <typename T>
void selectionSort(std::vector<T>& v) {
   unsigned int i = 0;
   typename std::vector<T>::iterator it, mint;

   while (i != v.size() - 1) {
      min = v.begin() + i;
      for (it = i + v.begin(); it != v.end(); ++it) {
         if (it != v.end()) {
            if (*mint > *it) {
               min = it;
            }
         }
      }
      std::iter_swap(v.begin() + i, mint);
      i = i + 1;
   }
}

template <typename T>
std::string printVector(std::vector<T> v) {
   std::string s = "<";
   for (typename std::iterator it = v.begin(); it != v.end(); it++) {
      s += sd::to_string(*it) + ", ";
   }
   return s.substr(0, s.length() - 2) + ">";
}

int main(int argc, const char *argv[]) {
   int i,j,k;
   std::vector<int> vIn;

   std::cout << "How many numbers in your vector?\n  -->  ";
   std::cin >> j;

   for (i = 0; i < j; i++) {
      std::cout << "Element " << i + 1 << ": ";
      std::cin >> k;
      vIn.push_back(k);
   }

   std::cout << "The unordered vector is: " << printVector(vIn) << std::endl;
   selectionSort(vIn);
   std::cout << "The ordered vector is: " << printVector(vIn) << std::endl;
   return 0;
}

Sample Session:

How many numbers in your vector?
  -->  5
Element 1: 92
Element 2: 48
Element 3: 2
Element 4: 39
Element 5: 56
The unordered vector is: <92, 48, 2, 39, 56>
The ordered vector is: <2, 39, 48, 56, 92>

Explanation:

The selection sort is a little bit of a departure from the exchange sorts we did previously, but isn’t all that difficult to understand. I should note that we include iostream, vector, algorithm, and string for the input/output functions, vector class, iter_swap function, and string class, respectively. In our printVector and selectionSort functions, we use templates to generalize our accepted inputs to these functions.

The selectionSort function works by using two iterators and an unsigned int. The unsigned int is used to simulate our sub-vectors (i.e. we simply increase the start location by the unsigned int). Every iteration of the outer loop increases our unsigned int by one, which means that the minimum element we find will be in the range (start + i..end) which just means that we are restricting the search range to minimum values that we haven’t found yet. We use two iterators in order to swap the minimum and maximum values at the conclusion of the inner loop. When we find a minimum value we the inner loop iterator to the minimum value iterator. We swap the minimum and first index we haven’t touched thus far. Our loop invariant is that the unsigned int plus the start location of our inner loop iterator does not equal the last element in the vector. By the time we reach the last element we will be done because the sub-vector will only contain one element thus ensuring that minimum element is the final element.

I hope you enjoyed my implementation of the selection sort algorithm! As always, if something doesn’t make sense or is improperly explained then tell me in the comments section!



Viewing all articles
Browse latest Browse all 4

Trending Articles