複雑さ以下の循環ソート配列内の特定の要素を検索したいと考えていますO(log n)
。
例: を検索13
し{5,9,13,1,3}
ます。
私の考えは、循環配列を通常の並べ替えられた配列に変換し、結果の配列でバイナリ検索を行うことでしたが、私の問題は、私が思いついたアルゴリズムがO(n)
最悪の場合にかかる愚かなことでした:
for(i = 1; i < a.length; i++){
if (a[i] < a[i-1]){
minIndex = i; break;
}
}
次に、i 番目の要素の対応するインデックスは、次の関係から決定されます。
(i + minInex - 1) % a.length
私の変換 (循環から通常への) アルゴリズムが O(n) かかる可能性があることは明らかなので、より良いものが必要です。
ire_and_curses のアイデアによると、Java での解決策は次のとおりです。
public int circularArraySearch(int[] a, int low, int high, int x){
//instead of using the division op. (which surprisingly fails on big numbers)
//we will use the unsigned right shift to get the average
int mid = (low + high) >>> 1;
if(a[mid] == x){
return mid;
}
//a variable to indicate which half is sorted
//1 for left, 2 for right
int sortedHalf = 0;
if(a[low] <= a[mid]){
//the left half is sorted
sortedHalf = 1;
if(x <= a[mid] && x >= a[low]){
//the element is in this half
return binarySearch(a, low, mid, x);
}
}
if(a[mid] <= a[high]){
//the right half is sorted
sortedHalf = 2;
if(x >= a[mid] && x<= a[high] ){
return binarySearch(a, mid, high, x);
}
}
// repeat the process on the unsorted half
if(sortedHalf == 1){
//left is sorted, repeat the process on the right one
return circularArraySearch(a, mid, high, x);
}else{
//right is sorted, repeat the process on the left
return circularArraySearch(a, low, mid, x);
}
}
うまくいけば、これはうまくいくでしょう。