Java中的排序數索引怎么利用分治算法實現?針對這個問題,這篇文章詳細介紹了相對應的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。
具體如下:
/**
* Find the first q and return the index
* First method is brutal force
* Second may
* be Divid and Conquer
*
* @author open201
*
*/
public class Ono {
/**
* f(n) = s.length = n;
*
* @param s
* @param q
* @return
*/
public static int BrutalForceSearch(int[] s, int q) {
for (int i = 0; i < s.length; i++) {
if (q == s[i])
return i;
}
return -1;
}
/**
* f(n) = log(n)
*
* @param s
* @param q
* @return
*/
public static int DCSearch(int[] s, int q, int startIndex, int endIndex) {
if (startIndex > endIndex)
return -1;
else {
int mid = (startIndex + endIndex) / 2;
if (s[mid] == q)
return mid;
else {
if (s[mid] > q)
return DCSearch(s, q, startIndex,mid-1);
else
return DCSearch(s, q, mid+ 1,endIndex);
}
}
}
public static void main(String[] args) {
int [] s = new int[10000000];
for(int i = 0;i<10000000;i++){
s[i] = i;
}
int q = 10000000-1;
long startTime = System.currentTimeMillis();
System.out.println(BrutalForceSearch(s, q));
long endTime = System.currentTimeMillis();
System.out.println(endTime-startTime);
startTime = System.currentTimeMillis();
System.out.println(DCSearch(s, q, 0, s.length - 1));
endTime = System.currentTimeMillis();
System.out.println(endTime-startTime);
}
}關于Java中的排序數索引怎么利用分治算法實現問題的解答就分享到這里了,希望以上內容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關注億速云行業資訊頻道了解更多相關知識。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。