`

Java 插入排序 (基于数组) 附图解

阅读更多
public class InsertSort {
	public void insertionSort(int[] arr, int length) {
		int unsortedIndex,location;
		int temp;
		for(unsortedIndex=1;unsortedIndex<length;unsortedIndex++){
			if(arr[unsortedIndex]<arr[unsortedIndex-1]){
				temp=arr[unsortedIndex];
				location=unsortedIndex;
				do{
					arr[location]=arr[location-1];
					location--;
				}while(location>0&&arr[location-1]>temp);
				arr[location]=temp;
			}
		}
	}
	public static void main(String[] args) {
		int arr[] = { 2, 568, 34, 46, 9, 23, 89, 43, 572, 684, 783, 543 };
		InsertSort is=new InsertSort();
		is.insertionSort(arr, 12);
		for (int i = 0; i < 12; i++) {
			System.out.print(arr[i] + ",");
		}
	}
}  

图解:

  • 大小: 112 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics