日期:2014-05-20 浏览次数:20770 次
for (i = 1; i < n; i++) { num = a[i]; while(num < a[i - 1]) { a[i] = a[i - 1]; break; } a[i] = num; }
------解决方案--------------------
用一维数组来做直接插入排序,时间复杂度是O(n2),要用双层的循环,里面的循环是用来移动数组元素位置的。直接插入排序建议用链表实现。
------解决方案--------------------
public class method {
public static void rank(int n) {
int a[] = new int[n];
Random rd = new Random();
for (int i = 0; i < n; i++) {
a[i] = rd.nextInt(1000);
}
int temp = 0;// 中间变量
int min = 0;// 最小值
int minIndex = 0;// 最小值下标
for (int i = 0; i < a.length; i++) {
min = a[i];
minIndex = i;
for (int j = i + 1; j < a.length; j++) {
if (a[j] < min) {
min = a[j];
minIndex = j;
}
}
temp = a[i];
a[i] = a[minIndex];
a[minIndex] = temp;
}
System.out.println("排序后数组为:");
for (int i = 0; i < n; i++)
System.out.print(a[i] + "\t");
}
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("输入随机数的个数");
String str = sc.next();
int n = Integer.parseInt(str);
rank(n);
}
}
------解决方案--------------------
//这里的循环有问题 for (i = 1; i < n; i++) { num = a[i]; while(num < a[i - 1]) { a[i] = a[i - 1]; break; } a[i] = num; }