[英]Question about quicksort with std::vector
Below are some code I found from internet which is using integer array for input. 以下是我从互联网上发现的一些代码,这些代码使用整数数组作为输入。 It is working well but if I change array to vector, it just print the original input 95, 45, 48, 98, 1, 485, 65, 478, 1, 2325. Can anyone explain the reason of it happens and how to fix it?
它工作正常,但是如果我将数组更改为vector,它只会打印原始输入95、45、48、98、1、485、65、478、1、2325。谁能解释它发生的原因以及如何解决它?
#include <iostream>
#include <vector>
using namespace std;
void printArray(vector<int> array, int n)
{
for (int i = 0; i < n; ++i)
cout << array[i] << endl;
}
void quickSort(vector<int> array, int low, int high)
{
int i = low;
int j = high;
int pivot = array[(i + j) / 2];
int temp;
while (i <= j)
{
while (array[i] < pivot)
i++;
while (array[j] > pivot)
j--;
if (i <= j)
{
temp = array[i];
array[i] = array[j];
array[j] = temp;
i++;
j--;
}
}
if (j > low)
quickSort(array, low, j);
if (i < high)
quickSort(array, i, high);
}
int main()
{
vector<int> array = {95, 45, 48, 98, 1, 485, 65, 478, 1, 2325};
int n = sizeof(array)/sizeof(array[0]);
cout << "Before Quick Sort :" << endl;
printArray(array, n);
quickSort(array, 0, n);
cout << "After Quick Sort :" << endl;
printArray(array, n);
return (0);
}
You are passing the vector by value to the quicksort
function, which causes it to operate on a copy of the input vector (hence the original vector remains unchanged). 您正在按值将向量传递给
quicksort
函数,这会使它对输入向量的副本进行操作(因此原始向量保持不变)。 A possible solution is to pass it by reference. 一个可能的解决方案是通过引用传递它。 So the declaration of
quicksort
should be: 因此,
quicksort
的声明应为:
void quickSort(std::vector<int> &array, int low, int high)
Another problem with the code is that sizeof(array)/sizeof(array[0])
is not the correct way to get the size of a vector, the valid way is to use the std::vector::size()
method (as also pointed out in H. Guijt's answer) 代码的另一个问题是
sizeof(array)/sizeof(array[0])
不是获取向量大小的正确方法,有效的方法是使用std::vector::size()
方法(正如H. Guijt的回答中指出的那样)
Bonus: use std::swap instead of that temp variable. 奖励:使用std :: swap代替该temp变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.