自定义向量和字符串类的快速排序实现

时间:2016-10-23 16:56:19

标签: c++ sorting quicksort

我正在努力实施一项家庭作业。在实现插入排序之后,我想再做一点并开始实现快速排序,并遇到了问题。

我实现的任何类型都应该读入文件中的单词列表,标记每个由空格分隔的单词,然后组织单词列表从最短到最长,然后按字母顺序排列。例如,如果输入的单词列表是

argument coding love waterbottle physics graduate pressure winning dream achieve can greatness madness clarity bliss b d e r

输出应为

b
d
e
r
can
love
bliss
dream
coding
achieve
clarity
madness
physics
winning
argument
graduate
pressure
greatness
waterbottle

使用插入排序工作正常。但是使用quicksort,我收到的结果很奇怪。

canument
baning
dream
lovembottle
winninge
graduate
pressure
physicse
achievettle
waterbottle
codingess
madnessss
blissss
greatness
clarityss
d
e
rrgument
argument

未分类的向量很奇怪,但我不太明白为什么会出现混淆的单词。

在阅读了quicksort之后,这就是我实施的内容。

template<class T>
int Vector<T>::partition(int first, int last)
{
  //pivot is index location at the end of vector
  int pivot = last;
  //low is first index location element of the vector
  int low = first;
  //high is last index before pivot
  int high =pivot-1;
  //as long as the value of data at index low is less than data at pivot, increment low
  while(data[low] < data[pivot])
  {
      low++;
  }
  //when the data at low count is higher than data at pivot index
  if(data[low] > data[pivot])
  {
      //as long as the data at high index has greater value than value at pivot index, decrement the high counter
      while(data[high] > data[pivot])
      {
          high--;
      }
      //when data at high index is less than data at pivot index,
      //swap the data at low index with data at high index
      if(data[high] < data[pivot])
      {
          T temp = data[low];
          data[low] = data[high];
          data[high] = temp;
      }
  }
  //when low index is == high index
  //swap data at high with data at pivot. Now the pivot data is in correct
  //index location. Return the location of pivot with index of high(where pivot now is)
  T pi = data[high];
  data[high] = data[pivot];
  data[pivot] = pi;
  return high;
}

template<class T>
void Vector<T>::quickSort(int start, int end)
{
  //if the start index is lower than end index,
  if(start < end)
  {
      //the index of pivot is given from the partition function
      int pi = partition(start, end);
      //recursive call for left half and right half of the remaining
      //elements.
      quickSort(start, pi-1);
      quickSort(pi+1, end);
  }
}

我很困惑,因为我不知道造成这个问题的原因。我应该看看我的String类吗?矢量类?或者这是实施中的问题?

感谢任何帮助。谢谢!

0 个答案:

没有答案