码迷,mamicode.com
首页 > 编程语言 > 详细

数据结构排序算法插入排序Java实现

时间:2019-04-15 16:25:54      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:rgs   temp   元素   \n   排序算法   step   str   oid   lse   

public class InsertDemo {

public static void main(String args[]) {


int[] sort ={4,2,1,3,6,5,9,8,10,7} ;
System.out.println("haha"+sort[0]);
System.out.println("排序前:");

print(sort);
shellSort(sort);
System.out.println("\n排序后:");
print(sort);

}



//直接插入排序
public static void insertSort(int[] a) {

for(int i=1;i<a.length;i++) {

int temp=a[i];
int j;
for(j=i-1; j>=0; j--) {
if(a[j]>temp) {
a[j+1]=a[j];
}
else {
break;
}
}
a[j+1]=temp;


}

}

public static void shellSort(int[] arrays) {

//增量每次都/2
for (int step = arrays.length / 2; step > 0; step /= 2) {

//从增量那组开始进行插入排序,直至完毕
for (int i = step; i < arrays.length; i++) {

int j = i;
int temp = arrays[j];

// j - step 就是代表与它同组隔壁的元素
while (j - step >= 0 && arrays[j - step] > temp) {
arrays[j] = arrays[j - step];
j = j - step;
}
arrays[j] = temp;
}
}

}



//打印
public static void print(int[] a){
for (int i = 0; i < a.length; i++) {
System.out.print(a[i]+" ");
}
}

}

数据结构排序算法插入排序Java实现

标签:rgs   temp   元素   \n   排序算法   step   str   oid   lse   

原文地址:https://www.cnblogs.com/ldcs/p/10710838.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!