【发布时间】:2018-03-04 03:35:40
【问题描述】:
我正在研究我最初的几个算法来培养我的 C++ 技能,目前正在编写一种使用归并排序计算反转的方法。我已经设法一起进行了有效的合并排序,但是在跟踪反转次数时遇到了一些麻烦。关于从这里去哪里的任何想法?如何跟踪这样的递归算法的反转次数?此外,我在互联网旅行中看到了一些不同的实现,并且发现大多数人都偏离了 std::vector 方法,知道为什么吗?感谢您的帮助,我的代码如下!
#include <iostream>
#include <math.h>
#include <vector>
using namespace std;
vector<int> print(vector<int> input){
for(int i=0; i<input.size(); i++){
cout<<input[i]<<",";
}
cout<<endl;
return input;
}
vector<int> merge(vector<int> left,vector<int> right){
//set up some varibles
vector<int> output;
int i=0;
int j=0;
//loop through the lists and merge
while(i<left.size() && j<right.size()){
//push the smallest of the two to the vector output
if(left[i]<=right[j]){
output.push_back(left[i]);
i+=1;
}
if(left[i]>right[i]){
output.push_back(right[j]);
j+=1;
}
}
//push the remnants of the vectors to output
for(i; i<left.size(); i++){
output.push_back(left[i]);
}
for(j; j<right.size(); j++){
output.push_back(right[j]);
}
return output;
}//end merge
vector<int> merge_sort(vector<int> input){
//check the size of the vector
if(input.size()<2){
return input;
}
else{
//int new vectors
vector<int> left;
vector<int> right;
vector<int> output;
//find the middle of the input vector
int middle=(input.size())/2;
//build the left vector
for(int i=0; i<middle; i++){
left.push_back(input[i]);
}
//build the right vector
for(int i=middle; i<input.size(); i++){
right.push_back(input[i]);
}
//make recursive calls
left=merge_sort(left);
right=merge_sort(right);
//call merge
output=merge(left,right);
return output;
}
}
int main()
{
vector<int> output;
vector<int> input;
input.push_back(2);
input.push_back(1);
input.push_back(10);
input.push_back(4);
output=merge_sort(input);
print(output);
}
【问题讨论】:
-
虽然这个问题很老了,但我有一些笔记:
1你一次问了太多问题。如果您有多个问题,请提出多个问题。 (也就是说,(1)算法是什么(已经描述了here),(2)如何实现它,以及(3)为什么人们不喜欢std::vector,注意(3)似乎意见-基于并因此偏离主题)2拥有一段代码不是很有用,您应该描述(1)您的代码正在做什么(包括错误消息,如果有的话),以及(2)您期望它做什么做。
标签: c++ algorithm c++14 mergesort