该代码适用于小num_items
,但溢出了num_items = 1000
的堆栈。
我认为1000是一个相当小的数字,所以应该有一种方法可以使这个工作达到更大的数字。我能做些什么来让它在更多的递归调用中存活下来?
#include <iostream>
#include <algorithm>
#include <vector>
#include <cstdlib>
#include <ctime>
void printv(std::vector<int>& v) {
for (int i=0; i<v.size(); i++) std::cout << v[i] << " ";
std::cout << std::endl;
}
void quicksort(std::vector<int>& v, int begin, int end) {
if (((end - begin) <= 1) ||
(begin < 0) ||
(end > (v.size() - 1))) return;
int pivot = v[std::rand() % v.size()];
int x = 0;
int y = v.size() -1;
while(x < y) {
int changed = 0;
if(v[x] <= pivot) {
x++;
changed = 1;
}
if (v[y] > pivot) {
y--;
changed = 1;
}
if (!changed){
std::swap(v[x], v[y]);
x++;
y--;
}
}
if (x == y) y++;
if (x > y) std::swap(x, y);
quicksort(v, begin, x);
quicksort(v, y, end);
}
int ran() {
return std::rand() % 100;
}
int main() {
std::srand(std::time(0));
int num_items = 1000;
std::vector<int> v (num_items);
std::generate_n(v.begin(), num_items, ran);
printv(v);
quicksort(v, 0, v.size()-1);
printv(v);
}
也欢迎关于代码的一般评论。
坚持[0,4]
:
#1 0x0000000000400b4c in quicksort (
v=std::vector of length 1000, capacity 1000 = {...}, begin=0, end=4)
at quicksort.cpp:14
#2 0x0000000000400cc1 in quicksort (
v=std::vector of length 1000, capacity 1000 = {...}, begin=0, end=4)
at quicksort.cpp:43
#3 0x0000000000400cc1 in quicksort (
v=std::vector of length 1000, capacity 1000 = {...}, begin=0, end=4)
at quicksort.cpp:43
#4 0x0000000000400cc1 in quicksort (
v=std::vector of length 1000, capacity 1000 = {...}, begin=0, end=4)
at quicksort.cpp:43
#5 0x0000000000400cc1 in quicksort (
v=std::vector of length 1000, capacity 1000 = {...}, begin=0, end=4)
at quicksort.cpp:43
#6 0x0000000000400cc1 in quicksort (
v=std::vector of length 1000, capacity 1000 = {...}, begin=0, end=4)
at quicksort.cpp:43
#7 0x0000000000400cc1 in quicksort (
v=std::vector of length 1000, capacity 1000 = {...}, begin=0, end=4)
at quicksort.cpp:43
答案 0 :(得分:3)
int pivot = v[std::rand() % v.size()];
int x = 0;
int y = v.size() -1;
您明确传递begin
和end
位置,但您从完整列表中选择了枢轴元素。这听起来不对。您应该在begin
和end
之间选择一个数据透视元素。此外,x
应从begin
开始,y
应从end
开始。否则,您总是在每个递归步骤中处理完整列表,这将解释您遇到的无限递归。