Skip to content

Instantly share code, notes, and snippets.

@qiuwei
Created March 10, 2014 22:38
Show Gist options
  • Save qiuwei/9475956 to your computer and use it in GitHub Desktop.
Save qiuwei/9475956 to your computer and use it in GitHub Desktop.
//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