这篇文章主要介绍了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); } }
Atas ialah kandungan terperinci Java排序数索引功能使用分治算法实现的示例. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!