天天看点

直接插入排序---java实现

思路:遍历无序的原数组,把第i个的后一个即i+1去与前面的i个逐个比较...

解法一:

package com.sheepmu.text;

import java.util.Arrays;
  /*   
  * @author sheepmu
  */ 
public class Sort {
	 public static void main(String[] args){
		 int[] arr={64,5,7,89,6,24};
		 insertSort(arr);
		 System.out.println(Arrays.toString(arr));
	 }	 	 
	 public static void insertSort(int[] arr){
		 int len=arr.length;
		 int temp=0;
		 for(int i=0;i<len-1;i++){//要len-1,不然后面i+1要越界。
			  temp=arr[i+1];	 
			  for(int  j=i;j>=0;j--){
				  if(temp<arr[j]){
					  arr[j+1]=arr[j];
					  arr[j]=temp;
					  }
			  }
			 
		 }
	 }
}	 
       

解法二:

package com.sheepmu.text;

import java.util.Arrays;
  /*   
  * @author sheepmu
  */ 
public class Sort {
public static void main(String[] args){
int[] arr={64,5,7,89,6,24};
insertSort(arr);
System.out.println(Arrays.toString(arr));
}  
public static void insertSort(int[] arr){
int len=arr.length;
int j,temp=0;
for(int i=0;i<len-1;i++){//要len-1,不然后面i+1要越界。
 temp=arr[i+1];
 j=i;
 while(j>=0&&temp<arr[j]){
 arr[j+1]=arr[j];
  j--;
 }
 arr[j+1]=temp;//因为上面运行完了后j--咯,所以这里是arr[j+1]=temp;而不是arr[j]=temp;
}
}
}