我只能使用负数来获取错误,而它适用于所有正数。不确定这里有什么问题。任何帮助/指导非常感谢。
#include <vector>
#include <iostream>
#include <algorithm>
int insertionSort(std::vector<int> &array){
// Count the number of shifts needed to sort the array
int shifts = 0;
for(int i = 1; i < array.size(); i++){
if(array[i] < array[i - 1]){
int j = i;
while(array[i] < array[i - 1] && i >= 0){
shifts++;
std::swap(array[i], array[i - 1]);
i--;
}
i = j;
}
}
return shifts;
}
int main(){
std::vector<int> array = {-1, -2}; // This won't work
//std::vector<int> array = {1, 2}; // This works
int shifts = insertionSort(array);
std::cout << shifts;
return 0;
}