我有以下代码。该方法应该有效,但我无法将 vector 传递给函数。我四处搜索,发现 vector 可以作为“引用”或“值”传递,我都试过了,但它们似乎没有用。我是否错误地调用了方法或以错误的方式传递了 vector ?无论哪种方式,我该怎么做才能解决这个问题?谢谢! :)
//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;
}
最佳答案
insertionSort(int arr[], int n) 方法的第一个参数错误。 您还错误地处理了 arr。在第一次迭代中,int j = 0 - 1 = -1;这是意外的/超出范围的。
请试试这个:
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;
}
}
谢谢!!!
关于c++ - 这里怎么调用InsertionSort方法呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36716136/