Median in Rotated Array
/***
find
median of rotated sorted array.
O(logn)
***/
#include<iostream>
using namespace std;
int find_start(int *a, int st, int ed) {
if(st >= ed) return st;
int mid = (st + ed) / 2;
if(a[mid] < a[mid-1]) return mid;
if(a[mid] > a[ed]) {
return find_start(a, mid+1, ed);
} else {
return find_start(a, st, mid-1);
}
}
int get_median(int *a, int sz) {
int m = sz/2;
int id = find_start(a, 0, sz-1);
cout<<"index:"<<id<<endl;
if(sz%2) {
if(id + m < sz)
return a[id+m];
else return a[m+id-sz];
} else {
if(id+m < sz)
return (a[id+m]+a[id+m-1])/2;
else if(id+m == sz)
return (a[0] + a[id+m-1])/2;
else return (a[m+id-sz] + a[m+id-sz-1])/2;
}
}
void main() {
int a[] = {1, 2, 3, 4, 5, 6, 7};
int sz = sizeof(a) / sizeof(int);
cout<<get_median(a,
sz)<<endl;
}
Comments
Post a Comment