這篇文章主要介紹了Java使用分治演算法實現排序數索引功能,結合具體實例形式分析了java分治演算法進行排序索引的相關操作技巧,需要的朋友可以參考下
#本文實例講述了Java使用分治演算法實作排序數索引功能。分享給大家參考,具體如下:
/** * Find the first q and return the index * First method is brutal force * Second may * be pid 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排序數索引功能使用分治演算法實現的範例的詳細內容。更多資訊請關注PHP中文網其他相關文章!