簡體   English   中英

在C ++中對Quicksort編程時出現分段錯誤

[英]Segmentation fault when programming Quicksort in C++

我正在嘗試用C ++編程此頁面上的第一個算法。 這是我將其適應這種語言時得到的:

void quicksort (vector<int>& numbers) {
      int leftSize = numbers.size() / 3
      , rightSize = numbers.size() - leftSize;
      vector<int>::iterator pivot = numbers.end() - rightSize; //Choose one third of the way through as the pivot.
      vector<int> left;
      vector<int> right;

      if(numbers.size() <= 1) {
          return;
      }

      //Place numbers less than the pivot on the left side and numbers greater on the right side
      for(vector<int>::iterator x = numbers.begin(); x < numbers.end(); x++) {
          if(*x < *pivot) {
              left.push_back(*x);
          } else {
              right.push_back(*x);
          }
      }

      quicksort(left);
      quicksort(right);

      //Concatenate the arrays
      numbers.clear();
      numbers.insert(numbers.end(), left.begin(), left.end());
      numbers.insert(numbers.end(), right.begin(), right.end());
}

但這給出了錯誤Segmentation fault (core dumped) 我僅在大小為20的矢量上對此進行測試,因此不應該是我的內存不足。 我能夠發現的是導致問題的是對quicksort(right)的調用。 僅注釋掉該行並留下quicksort(left)不會產生運行時錯誤(盡管向量顯然不會排序)。

有什么想法為什么quicksort(left)會起作用,而不是quicksort(right)嗎?

如果選擇向量的最小元素作為樞軸,則所有元素(包括樞軸)都將進入right 然后,您可以在right上調用quicksort ,它與您之前使用的是同一矢量。 給每個呼叫quicksort使得以相同的呼叫quicksort ,你很快超過堆棧的最大深度,並得到一個段錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM