[英]How do I call the InsertionSort method here?
I have the following code.. The method should work but I'm having trouble passing the vector to a function. 我有以下代码。该方法应该可以工作,但是在将向量传递给函数时遇到了麻烦。 I searched around and found that vector can be passed as 'references' or 'values' and I tried both, but they didn't seem to work.
我四处搜索,发现矢量可以作为“引用”或“值”传递,我尝试了两者,但它们似乎没有用。 Am I calling the method incorrectly or passing the vector in a wrong way?
我是错误地调用方法还是以错误的方式传递向量? Either ways, what can I do to fix this?
无论哪种方式,我该怎么做才能解决? Thanks!
谢谢! :)
:)
//insertion sort method
#include <iostream>
#include <vector>
using namespace std;
void insertionSort(int arr[], int n){
for(int i = 0; i < n; i++){
int temp = arr[i]; // element adjacent to left sorted array
int j = i - 1;
while(temp > arr[j] && j != 0){
arr[j] = arr[j - 1];
j--;
}
arr[j] = temp;
}
}
int main(){
int n, temp;
cin >> n;
vector <int> arr;
for(int i = 0; i < n; i++){
cin >> temp;
arr.push_back(temp);
}
insertionSort(arr, n);
for(int i = 0; i < n; i++)
cout << arr[i] << " ";
return 0;
}
The first parameter of the insertionSort(int arr[], int n) method is wrong. insertSort(int arr [],int n)方法的第一个参数错误。 You also processed the arr incorrectly.
您还错误地处理了arr。 At first iteration, int j = 0 - 1 = -1;
第一次迭代时,int j = 0-1 = -1; which is unexpected/ out of bound.
这是意外/超出范围的。
Please try this : 请尝试这个:
void insertionSort(vector <int> &arr, int n){
int i, j, temp;
for (i = 1; i < n; i++)
{
temp = arr[i];
j = i - 1;
while ((j >= 0) && (temp<arr[j]))
{
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = temp;
}
}
Thanks !!! 谢谢 !!!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.