这是我在c ++中使用向量进行合并排序的代码。但它给我带来了奇怪的结果:
结果:
输入元素:11 33 12 44 99 34
分类元素:11 33 33 44 99 99
My Header File没什么特别的:“stdafx.h”
#pragma once
#include "targetver.h"
#include <stdio.h>
#include <tchar.h>
#include <iostream>
using namespace std;
代码:
#include "stdafx.h"
#include <iostream>
#include<array>
#include<vector>
//#define array_size(array) (sizeof((array))/sizeof((array[0])))
using namespace std;
template <typename T>
void merge_sort(vector<T>& arr, vector<T>& arr1, vector<T>& arr2) {
arr.clear();
int i = 0, j = 0, k = 0;
for (i = 0; i < arr1.size() && j < arr2.size(); k++) {
if (arr1.at(i) <= arr2.at(j)) {
arr.push_back(arr1.at(i));
i++;
}
else if (arr1.at(i) > arr2.at(j)) {
arr.push_back(arr1.at(j));
j++;
}
k++;
}
while (i < arr1.size()) {
arr.push_back(arr1.at(i));
i++;
}
while (j < arr2.size()) {
arr.push_back(arr2.at(j));
j++;
}
};
template <typename T>
vector<T>merge(std::vector<T>& arr) {
if (1 < arr.size()) {
vector<T> arr1(arr.begin(), arr.begin() + arr.size() / 2);
merge(arr1);//dividing to size 1
std::vector<T> arr2(arr.begin() + arr.size() / 2, arr.end());
merge(arr2);
merge_sort(arr, arr1, arr2);
}
return (arr);
//write_vector(arr);
};
int main()
{
//Merge Sort
vector<int> inputVec;
int size = 6;
for (int i = 0; i < size; i++) {
int input;
cin >> input;
inputVec.push_back(input);
}
vector<int>& newSort=merge(inputVec);
vector<int>::iterator it;
for (it = newSort.begin(); it != newSort.end(); ++it)
cout<<endl<< *it << endl;
return 0;
}
结果窗口: My Output 有人可以指出有什么问题吗?为什么它会创建重复的元素?
答案 0 :(得分:0)
在merge_sort
函数中查看您的代码:
for (i = 0; i < arr1.size() && j < arr2.size(); k++) {
if (arr1.at(i) <= arr2.at(j)) {
arr.push_back(arr1.at(i));
i++;
}
else if (arr1.at(i) > arr2.at(j)) {
arr.push_back(arr1.at(j));
// ^^^^
// It should be arr.push_back(arr2.at(j));
j++;
}
k++;
}
将arr.push_back(arr1.at(j));
替换为arr.push_back(arr2.at(j));
,您的代码就像魅力一样。