1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
|
#include<iostream>
#include<vector>
#include <cstdlib>
using namespace std;
void minfind(vector<int> &array,int left,int right, int &min, int &next_min);
int main(){
cout << "Enter integers one line at a time. (Enter -999 to terminate)" << endl;
vector<int> array; // you can also use an array to do this, e.g., int A[21];
int input;
//let user enter till termination condition
while(true){
cin >> input;
if(input == -999) //check for termination condition
break;
array.push_back(input);
}
int imin = 0;
int imax = array.size();
int q;
int r;
minfind(array, imin, imax, q, r);
cout<<"Min number is " << r <<endl;
cin.get();
system("pause");
return 0;
}
void minfind(vector<int> &array,int left,int right, int &min, int &next_min)
{
int a;
int b;
int c;
int d;
if(left == right){
min = array[left];
next_min = 2147483647;
}
else {
int mid= (right+left)/2;
minfind(array,left,mid,a,b);
minfind(array,mid+1,right,c,d);
if (a<b){
min = a;
if (b<c && b<d)
next_min = b;
}
else if (b<a){
min = b;
if (a<c&& a<d)
next_min = a;
}
if (c<d){
min = c;
if (d<a && d<b)
next_min = d;
}
else if (d<c){
min = d;
if (c<a && c<b)
next_min = c;
}
}
}
|