fork download
  1. #include <time.h>
  2. #include <cstdlib>
  3. #include <vector>
  4. #include <iostream>
  5. using namespace std;
  6.  
  7. vector<int> sortedVec;
  8.  
  9. int main() {
  10. // Random seed
  11. srand(time(NULL));
  12.  
  13. // Put in n random elements
  14. for (int i = 0; i < 5; i++) sortedVec.push_back((i+1)*11);
  15.  
  16. // Sort the vector
  17. bool swapped = true;
  18. int endDecrement = 0;
  19. while (swapped) {
  20. swapped = false;
  21. endDecrement++;
  22. for (int i = 0; i < sortedVec.size()-endDecrement; i++) {
  23. if (sortedVec.at(i) > sortedVec.at(i+1)) {
  24. int swap = sortedVec.at(i);
  25. sortedVec.at(i) = sortedVec.at(i+1);
  26. sortedVec.at(i+1) = swap;
  27. swapped = true;
  28. }
  29. }
  30. }
  31.  
  32. cout<<"Sorted random list:"<<endl;
  33. for (int i = 0; i < sortedVec.size(); i++) cout<<sortedVec.at(i)<<endl;
  34.  
  35. int toInsert = 30;
  36. cout<<"Random element to insert = "<<toInsert<<endl;
  37.  
  38. // Insert a random int to the sorted vector
  39. int minIndex = 0;
  40. int maxIndex = sortedVec.size()-1;
  41. while (true) {
  42.  
  43. int mid = (maxIndex-minIndex)>>1;
  44. cout << minIndex << " " << mid << " " << maxIndex << endl;
  45. cout << "mid val = " << sortedVec.at(mid) << endl;
  46. if (toInsert == sortedVec.at(mid) || maxIndex-minIndex < 2) {
  47. sortedVec.insert(sortedVec.begin()+mid, toInsert);
  48. break;
  49. }
  50. else if (toInsert < sortedVec.at(mid)) maxIndex = mid;
  51. else if (toInsert > sortedVec.at(mid)) minIndex = mid;
  52. }
  53.  
  54. cout<<"Random list with inserted element:"<<endl;
  55. for (int i = 0; i < sortedVec.size(); i++) cout<<sortedVec.at(i)<<endl;
  56.  
  57. return 0;
  58. }
  59.  
Success #stdin #stdout 0.01s 2816KB
stdin
Standard input is empty
stdout
Sorted random list:
11
22
33
44
55
Random element to insert = 30
0  2  4
mid val = 33
0  1  2
mid val = 22
1  0  2
mid val = 11
Random list with inserted element:
30
11
22
33
44
55