1

my output is below, bubble sort partially sorting, 'Battle Start Galatica' is one string

before sorting,

cats dogs monkey pear bears beat beets Battle Start Galatica bear bears be bee zebra cantaloupe cactus

after sorting,

bear bears be bears beat beets Battle Start Galatica bee zebra cantaloupe cactus cats dogs monkey pear

Hello, World!

#include <iostream>
#include <vector>
#include "Sort.h"

int main() {
  std::vector<std::vector<std::vector<std::string> > >
  v1{ {{"cats", "dogs", "monkey", "pear"}, {"bears", "beat", "beets", 
        "Battle Start Galatica"}},
      {{"bear", "bears", "be"}, {"bee", "zebra"}, {"cantaloupe", 
        "cactus"}}};

  std::cout << "before sort" << std::endl;
  std::cout << v1 << std::endl;

  sort(v1);

  std::cout << "after sort" << std::endl;
  std::cout << v1 << std::endl;
  std::cout << "Hello, World!" << std::endl;
  return 0;
}

i turn the vector into a vector and try and sort it using bubble sort

template <typename T>
void sort(std::vector<T>& v)
{
  for(int i = 0; i < v.size();i++)
  {
      bool swapped = false;
      for(int j = 0; j < v.size()-i-1;j++)
      {
          if(v[j]>v[j+1])
          {
              swap(v,j,j+1);
              swapped = true;
          }
      }
      if(!swapped) break;
  }
}

with the following swap method

template <typename T>
void swap(std::vector<T>& v, int i, int j)
{
    T temp = v[i];
    v[i] = v[j];
    v[j] = temp;
}

What method will sort completely or what method in addition to bubble?

SouvikMaji
  • 1,088
  • 3
  • 22
  • 39
  • I'd use std::sort myself; or std::stable_sort depending on requirements – UKMonkey Mar 14 '18 at 10:57
  • @UKMonkey Practicing building sort functions – Isaiah Spearman Mar 14 '18 at 10:58
  • 4
    You have 3 levels of vector and it is only sorting the first one. Remove the `std::vector > >` and do just `std::vector` – Amadeus Mar 14 '18 at 11:00
  • Aside: take a look at [`iter_swap`](http://en.cppreference.com/w/cpp/algorithm/iter_swap) and [writing sort algorithms](https://stackoverflow.com/questions/24650626/how-to-implement-classic-sorting-algorithms-in-modern-c) – Caleth Mar 14 '18 at 11:21

0 Answers0