您的位置:首页 > 编程语言 > Java开发

JAVA排序算法---直接插入排序

2016-03-11 11:38 337 查看
package 备份类;

/**
* 插入排序算法
*/
public class 插入排序 {
public static void main(String[] args) {

int[] a = { 7, 6, 5, 4, 5, 7, 8, 4, 3 };
outArr(a);
insertSort(a);
outArr(a);
}

/**
* 备份当前的元素,只要前面的元素<当前的元素就向后移动一位
*/
public static void insertSort(int[] a) {
int i, j, temp;
for (i = 0; i < a.length - 1; i++) {
// a[i+1]就是当前的对象:比较哨
temp = a[i + 1];
j = i;
// 向后移动一位
while (j > -1 && temp <= a[j]) {
a[j + 1] = a[j];
j--;
}
// 把备份的这个放在移动之后空出的那一位上
a[j + 1] = temp;
}
}

/**
* 打印当前的数组
*/
public static void outArr(int[] a) {
int n = a.length;
for (int i = 0; i < n; i++) {
System.out.print(a[i] + " ");
}
System.out.println();
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: