我编写了一个C++程序,目的是将元素快速插入到已排序的向量中。它有时但并非全部都有效,我一直无法弄清楚原因。当我用纸和铅笔执行算法时,算出来了,但有些问题是错误的。请帮忙?将元素插入已排序的向量中
#include <time.h>
#include <cstdlib>
#include <vector>
#include <iostream>
using namespace std;
vector<int> sortedVec;
int main() {
// Random seed
srand(time(NULL));
// Put in n random elements
for (int i = 0; i < 10; i++) sortedVec.push_back(rand()%10);
// Sort the vector
bool swapped = true;
int endDecrement = 0;
while (swapped) {
swapped = false;
endDecrement++;
for (int i = 0; i < sortedVec.size()-endDecrement; i++) {
if (sortedVec.at(i) > sortedVec.at(i+1)) {
int swap = sortedVec.at(i);
sortedVec.at(i) = sortedVec.at(i+1);
sortedVec.at(i+1) = swap;
swapped = true;
}
}
}
cout<<"Sorted random list:"<<endl;
for (int i = 0; i < sortedVec.size(); i++) cout<<sortedVec.at(i)<<endl;
int toInsert = rand()%10;
cout<<"Random element to insert = "<<toInsert<<endl;
// Insert a random int to the sorted vector
int minIndex = 0;
int maxIndex = sortedVec.size()-1;
while (true) {
int mid = (maxIndex-minIndex)>>1;
if (toInsert == sortedVec.at(mid) || maxIndex-minIndex < 2) {
sortedVec.insert(sortedVec.begin()+mid, toInsert);
break;
}
else if (toInsert < sortedVec.at(mid)) maxIndex = mid;
else if (toInsert > sortedVec.at(mid)) minIndex = mid;
}
cout<<"Random list with inserted element:"<<endl;
for (int i = 0; i < sortedVec.size(); i++) cout<<sortedVec.at(i)<<endl;
return 0;
}
为什么不使用'std :: set'来为你排序元素?而事件如果你想使用向量,你可以使用'std :: sort'实现排序,并使用'std :: equal_range'算法找到要插入的位置,而不是写你自己的。 – Naveen
如果你打算这样做,有没有理由不使用'std :: sort'来进行排序,'std :: upper_bound'来找到你的插入点? (但是如果你想按顺序插入,这实际上不是最好的方法,IMO)。 –
@Jerry Coffin,这是一个虚拟程序,用于解决不同程序中的相同问题。另一个程序执行A *搜索并将新节点插入名为tree的向量中。问题是我不知道如何使用std :: upper_bound和Node类的值(我是C++的新手)。 Node类有一个名为fVal的int,这是我想用来确定向量的插入位置的东西。如果我能得到std :: upper_bound来检查tree.at(无论什么位置).fVal那会很棒。 – asimes