A Quicksort function template - C++ Data Structure

C++ examples for Data Structure:Sort

Description

A Quicksort function template

Demo Code

#include <iostream>
#include <iomanip>
#include <vector>

template<typename T>
inline void swap(std::vector<T>& data, int first, int second){
  T temp {data[first]};//  w  ww. j av a  2  s .  c  o  m
  data[first] = data[second];
  data[second] = temp;
}

template<typename T>
void sort(std::vector<T>& data, int start, int end)
{
  if (!(start < end))
    return;

  // Choose middle address to partition set
  swap(data, start, (start + end) / 2);                            // Swap middle address with start

  int current {start};
  for (int i {start + 1}; i <= end; ++i)
  {
    if (data[i] < data[start])                                     // Is word less than chosen word?
      swap(data, ++current, i);                                    // Yes, so swap to the left
  }

  swap(data, start, current);                                      // Swap the chosen word with last in

  if (current > start)
     sort(data, start, current - 1);             // Sort left subset if exists
  if (end > current + 1)
     sort(data, current + 1, end);             // Sort right subset if exists
}

// Sort all vector elements
template<typename T>
inline void sort(std::vector<T>& values)
{
  sort(values, 0, values.size() - 1);
}

// Output vector elements
template<typename T>
void list(std::vector<T> values, int width = 5)
{
  for (auto value : values)
    std::cout << std::setw(width) << value;
  std::cout << std::endl;
}

int main()
{
  std::vector<int> numbers {-12, 14, -15, 16, 110, -410, 156, 14, 167, 145};
  list(numbers);
  sort(numbers);
  std::cout << "\n Sorted integers:\n";
  list(numbers);

  std::vector<char> letters {'H', 'w', 'l', 'l', 'a', 'v', 'e', 'q', '2', '1'};
  list(letters, 2);
  sort(letters);
  std::cout << "\n Sorted characters:\n";
  list(letters, 2);

  std::cout << "\nFloating-point values to be sorted:\n";
  std::vector<double> values {-21.5, 11.4, -21.55, 61.3, 10.11, -40.51, 56.10, 41.7, 67.13, 45.10};
  list(values, 10);
  sort(values);
  std::cout << "\n Sorted floaating-point values:\n";
  list(values, 10);

}

Result


Related Tutorials