标签:pack bin array import for 高效 compare new direct
一、直接插入排序
package algorithm.sort.compare.insert; import java.util.Arrays; public class DirectInsertSort { public static void main(String[] args) { int[] arrayA = new int[] {11, 213, 134, 65, 77, 78, 23, 43}; directInsertSort (arrayA); System.out.println (Arrays.toString (arrayA)); } public static void directInsertSort ( int[] array ){ for ( int i = 1; i < array.length; i++ ){ int j; int temp = array[i]; for ( j = i; j > 0; j-- ){ if (array[j - 1] > temp) array[j] = array[j - 1]; else break; } array[j] = temp; } } }
二、折半插入排序
折半插入排序(binary insertion sort)是对插入排序算法的一种改进。
package algorithm.sort.compare.insert;
import java.util.Arrays;
public class BinaryInsertSort {
public static void main(String[] args) {
int[] arrayA = new int[] { 11, 213, 134, 65, 77, 78, 23, 43 };
binaryInsertSort (arrayA);
System.out.println (Arrays.toString (arrayA));
}
private static void binaryInsertSort ( int[] array ){
for ( int i = 1; i < array.length; i++ ){
// if (array[i] > array[i - 1]) // 从大到小
if (array[i] < array[i - 1]){ // 从小到大
int tmp = array[i];
int low = 0;
int high = i - 1;
while (low <= high){
int mid = ( low + high ) >>> 1;
// if (array[mid] > tmp) // 从大到小
if (array[mid] < tmp)// 从小到大
low = mid + 1;
else
high = mid - 1;
}
for ( int j = i; j > low; j-- )
array[j] = array[j - 1];
array[low] = tmp;
}
}
}
}
三、希尔排序
希尔排序(Shell Sort)是插入排序的一种。也称缩小增量排序,是直接插入排序算法的一种更高效的改进版本。
package algorithm.sort.compare.insert; import java.util.Arrays; public class ShellSort { public static void main(String[] args) { int[] arrayA = new int[] { 213, 134, 65, 77, 78, 23, 43 }; shellSort (arrayA, 0, arrayA.length); System.out.println (Arrays.toString (arrayA)); } private static void shellSort ( int[] array, int start, int len ){ int power = 1; while (( power + 1 ) * 2 < len) power = ( power + 1 ) * 2 - 1; for ( int k = power; k >= 1; k = ( k + 1 ) / 2 - 1 ){ for ( int i = 0; i < k; i++ ){ if (len - i <= 1) break; int tmp; for ( int j = start + i + k; j < start + len; j += k ){ tmp = array[j]; int m = j; for ( ; m > start + i; m -= k ) { if (array[m - k] > tmp) // 从小到大 array[m] = array[m - k]; else break; } array[m] = tmp; } } } } }
标签:pack bin array import for 高效 compare new direct
原文地址:http://www.cnblogs.com/chen-yonghai/p/6367427.html