package com.algorithm.sort; public class BinaryInsertSort { /** * 使用二分查找法 进行插入排序 * 时间复杂度为:n*lgn * @param args */ public static void main(String[] args) { int[] sourceArray = {100, 22,42,12,73,24,15,31,27,48,9}; BinaryInsertSort bis = new BinaryInsertSort(); int[] targetArray = bis.sort(sourceArray); for (int i = 0; i < targetArray.length; i++) { int j = targetArray[i]; System.out.println(j); } } private int[] sort(int [] sourceArray){ for (int i = 1; i < sourceArray.length; i++) { System.out.println("==================================" + i); sort(sourceArray, i, 0, i-1);//将位置i的数据插入到数据 0~i-1位中 } return sourceArray; } /** * 将sourceArray中第i个元素插到正确0~i-1中的某个位置 */ private void sort(int[] sourceArray, int i, int low, int high){ if(sourceArray[high] > sourceArray[i]){//如果第i-1位大于第i位,则需要进行查找 int temp = sourceArray[i]; while(low <= high && high > 0){ int middle = (low + high)/2; if(sourceArray[middle] > temp){ high = middle - 1; }else{ low = middle + 1; } } for (int j = i; j > low; j--) { sourceArray[j] = sourceArray[j-1]; } sourceArray[low] = temp; } } }
排序算法(三)二分查找插入排序
猜你喜欢
转载自renegade24.iteye.com/blog/1669390
今日推荐
周排行