您的位置:首页 > 其它

随机输入十个数,采用直接插入进行排序

2015-08-28 17:31 274 查看
import java.util.Scanner;

public class Test2 {
public static void main(String[] args) {
//int[] a = { 4, 8, 6, 7, 6, 13, 27, 64, 1 };

Scanner scanner = new Scanner(System.in);
int[] a = new int[10];
for (int i = 0; i < 10; i++) {
a[i] = scanner.nextInt();
}

System.out.println("排序之前:");
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
// 直接插入排序
for (int i = 1; i < a.length; i++) {
// 待插入元素
int temp = a[i];
int j;
for (j = i - 1; j >= 0; j--) {
// 将大于temp的往后移动一位
if (a[j] > temp) {
a[j + 1] = a[j];
} else {
break;
}
}
a[j + 1] = temp;
}
System.out.println();
System.out.println("排序之后:");
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: