Created
March 10, 2014 22:38
-
-
Save qiuwei/9475956 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//search the element which has the minimal abs value in an ascending array | |
#include <iostream> | |
#include <cmath> | |
#include <vector> | |
using namespace std; | |
int minabs(vector<int> &a, int start, int end){ | |
if(start+1 == end){ | |
return a[start]; | |
}else if(start+2 == end){ | |
return abs(a[start]) < abs(a[start+1]) ? a[start] : a[start+1]; | |
}else if(a[start] * a[end-1] > 0){ | |
return abs(a[start]) < abs(a[end-1]) ? a[start] : a[end-1]; | |
}else{ | |
int middle = (start+end)/2; | |
int leftmin = minabs(a, start, middle); | |
int rightmin = minabs(a,middle, end); | |
return abs(leftmin)< abs(rightmin)?leftmin:rightmin; | |
} | |
} | |
int main(){ | |
vector<int> array; | |
int buf = 0; | |
while(cin>>buf){ | |
array.push_back(buf); | |
} | |
cout << minabs(array, 0, array.size()) << endl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment