public class QuickSearch { public static int getMiddle(List<Integer> list, int low, int high) { Integer temp = list.get(high); while (low < high) { while (low < high && list.get(low) < temp) { low++; } list.set(high, list.get(low)); while (low < high && list.get(high) > temp) { high--; } list.set(low, list.get(high)); if (list.get(high) == temp) { break; } } list.set(high, temp); return low; } //先定位3个点 public static void quickSearch(List<Integer> list, int low, int high) { if (low < high) { int target = getMiddle(list, low, high); if (target<2) { return; } int middle = getMiddle(list, low, target-1); int lwoMiddle = 0; if (middle>0) { lwoMiddle = getMiddle(list, low, middle-1); } int highMiddle = target-1; if(middle+1 != target){ highMiddle = getMiddle(list, middle+1, target-1); } int lowLow = low; int lowHigh = target-1; int highLow = target+1; int highHigh = high; numSearch(list,target,lwoMiddle,highMiddle,lowLow,lowHigh,highLow,highHigh); } } //找出匹配的相加项 public static void numSearch(List<Integer> list,int target,int lwoMiddle,int highMiddle,int lowLow, int lowHigh,int highLow,int highHigh){ Integer targetNum = list.get(target); Integer lwoMiddleNum = list.get(lwoMiddle); Integer highMiddleNum = list.get(highMiddle); boolean flag = true; while(flag){ if (lwoMiddleNum + highMiddleNum > targetNum) { recursionSearch(list,lwoMiddle+1,lowHigh,highLow,highMiddle-1,target); recursionSearch(list,lowLow,lwoMiddle-1,highMiddle+1,highHigh,target); recursionSearch(list,lowLow,lwoMiddle-1,highLow,highMiddle-1,target); }else if (lwoMiddleNum + highMiddleNum < targetNum) { recursionSearch(list,lwoMiddle+1,lowHigh,highMiddle+1,highHigh,target); } else{ System.out.println(lwoMiddleNum+" + "+highMiddleNum+" = "+targetNum); flag = false; } } } public static void recursionSearch(List<Integer> list, int lowLow, int lowHigh,int highLow,int highHigh,int target){ int lwoMiddle = -1; int highMiddle = -1; if (lowLow < lowHigh) { lwoMiddle = getMiddle(list, lowLow, lowHigh); } if (highLow < highHigh) { highMiddle = getMiddle(list, highLow, highHigh); } if (lwoMiddle == -1 || highMiddle == -1 ) { return; } numSearch(list,target,lwoMiddle,highMiddle, lowLow, lowHigh, highLow, highHigh); } public static void quick(List<Integer> list,int search) { list.add(search); if (list.size() > 0) { quickSearch(list, 0, list.size() - 1); } } public static void main(String[] args) { List<Integer> list = new ArrayList<Integer>(); list.add(14); list.add(3); list.add(12); list.add(1); list.add(9); list.add(7); list.add(11); list.add(10); list.add(5); list.add(6); quick(list, 10); } }
复杂度:N+(N/2)lg(N/2)。
时间: 2024-10-10 03:38:54