Java数据结构及算法实例:插入排序 Insertion Sort
/**
*选择排序的思想:
*每次循环前,数组左边都是部分有序的序列,
*然后选择右边待排元素,将其值保存下来
*依次和左边已经排好的元素比较
*如果小于左边的元素,就将左边的元素右移一位
*直到和最左边的比较完成,或者待排元素不比左边元素小
*/
packageal;
publicclassInsertionSort{
publicstaticvoidmain(String[]args){
InsertionSortinsertSort=newInsertionSort();
int[]elements={14,77,21,9,10,50,43,14};
//sortthearray
insertSort.sort(elements);
//printthesortedarray
for(inti=0;i<elements.length;i++){
System.out.print(elements[i]);
System.out.print("");
}
}
/**
*@author
*@paramarray待排数组
*/
publicvoidsort(int[]array){
//mintosavetheminimumelementforeachround
intkey;//savecurrentelement
for(inti=0;i<array.length;i++){
intj=i;//currentposition
key=array[j];
//comparecurrentelement
while(j>0&&array[j-1]>key){
array[j]=array[j-1];//shiftit
j--;
}
array[j]=key;
}
}
}
热门推荐
10 参加儿子大学祝福语简短
11 开店送礼祝福语大全简短
12 职场离职文案祝福语简短
13 姐妹分手了祝福语简短
14 写给男生简短的祝福语
15 生女儿的祝福语简短
16 朋友花篮开业祝福语简短
17 送个姐妹生日祝福语简短
18 女神节日简短祝福语大全