参考的是这个博客,想自己实现一遍,结果不停的报错不知道为什么
#include <iostream>
#include <vector>
void merge(std::vector<int> &nums, int start, int end, std::vector<int> &res);
void mergeSort(std::vector<int> &nums, int start, int end, std::vector<int> &res) {
if (end - start == 1) {
if (nums[start] > nums[end]) {
std::swap(nums[start], nums[end]);
return;
}
} else if (end - start == 0) {
return;
} else {
mergeSort(nums, start, start + (end - start + 1) / 2, res);
mergeSort(nums, (end - start + 1) / 2 + start + 1, end, res);
merge(nums, start, end, res);
}
};
void merge(std::vector<int> &nums, int start, int end, std::vector<int> &res) {
int leftLen = (end - start + 1) / 2 + 1;
int leftIdx = start;
int rightIdx = start + leftLen;
int resIdex = start;
while (leftIdx < start + leftLen && rightIdx < end + 1) {
if (nums[leftIdx] <= nums[rightIdx]) {
//运行到这里报错,我尝试了下没有超过界限啊
std::cout << "11" << std::endl;
res[resIdex++] = nums[leftIdx++];
} else {
std::cout << "12" << std::endl;
res[resIdex++] = nums[rightIdx++];
}
}
while (leftIdx < start + leftLen) {
std::cout << "2" << std::endl;
res[resIdex++] = nums[leftIdx++];
}
while (rightIdx < end + 1) {
std::cout << "3" << std::endl;
res[resIdex++] = nums[rightIdx++];
}
}
int main(int argc, char const *argv[])
{
std::vector<int> nums = {1, 5, 7, 3 ,8, 3, 5, 6, 8, 11};
int n = nums.size();
std::cout << "Original Nums is" << std::endl;
for (auto num : nums) {
std::cout << num << ",";
}
std::cout << std::endl;
std::vector<int> res;
mergeSort(nums, 0, n - 1, res);
std::cout << "Sorted Nums is" << std::endl;
for (auto num : res) {
std::cout << num << ",";
}
std::cout << std::endl;
return 0;
}
显示结果为:
Original Nums is
1,5,7,3,8,3,5,6,8,11,
1
5
0,2,2,0,2,0,
1
11
段错误 (核心已转储)