我编写了一个 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;
}