Insert Sort
排序算法——插入排序
基本介绍
插入式排序属于内部排序法,是对于欲排序的元素以插入的方式找寻该元素的适当位置,以达到排序的目的
思路图解图
代码
算法代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| public static void insertSorting(int [] arr){
for( int i = 1; i < arr.length; i++) { int insertValue = arr[ i ]; int insertIndex = i - 1;
while (insertIndex >= 0 && insertValue < arr[ insertIndex ]) { arr[ insertIndex + 1 ] = arr[ insertIndex ]; insertIndex--;
} if ( insertIndex!=i-1 ) { arr[ insertIndex + 1 ] = insertValue; }
} System.out.println ( Arrays.toString ( arr ) ); }
|
性能测试
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
| public class InsertSorting { public static void main ( String[] args ) {
int arr[] = new int[ 80000 ]; randomArr ( arr ); System.out.println ("插入排序所用时间" ); String date1String = Date ( ); System.out.println ("排序前时间是:"+date1String ); insertSorting ( arr ); String date2String = Date ( ); System.out.println ("排序后时间是:"+date2String ); }
public static void insertSorting(int [] arr){
for( int i = 1; i < arr.length; i++) { int insertValue = arr[ i ]; int insertIndex = i - 1;
while (insertIndex >= 0 && insertValue < arr[ insertIndex ]) { arr[ insertIndex + 1 ] = arr[ insertIndex ]; insertIndex--;
} if ( insertIndex!=i-1 ) { arr[ insertIndex + 1 ] = insertValue; }
}
} private static void randomArr ( int[] arr ) { for(int i = 0; i < arr.length;i++){ arr[ i ] = (int) ( Math.random ( ) * 8000000 ); } }
private static String Date ( ) { Date date1 = new Date ( ); SimpleDateFormat simpleFormatter = new SimpleDateFormat ( "HH:mm:ss" ); return simpleFormatter.format(date1 ); } }
|
思考
数组 arr = {2,3,4,5,6,1} 这时需要插入的数 1(最小), 这样的过程是:
{2,3,4,5,6,6}
{2,3,4,5,5,6}
{2,3,4,4,5,6}
{2,3,3,4,5,6}
{2,2,3,4,5,6}
{1,2,3,4,5,6}
结论: 当需要插入的数是较小的数时,后移的次数明显增多,对效率有影响.