Java 数字排序为什么错了

来源:百度知道 编辑:UC知道 时间:2024/06/07 06:34:09
public class Paixu {
public static void main(String[] args) {
int[] n= { 13, 11, 21, 45, 20, 15, 1 };

for (int i = 0; i < n.length; i++) {

if (n[i]> n[i+1]) {
int x = n[i+1];
n[i+1] = n[i];
n[i] = x;

}}
for (int i = 0; i < n.length; i++) {
System.out.print(n[i] + ",");
}
}
}

话说单循环如何实现冒泡排序..
何况当i=n.length-1时,n[i+1]的下标为n.length会发生越界
下为修改后的代码:

public class BubbleSort {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] n = { 13, 11, 21, 45, 20, 15, 1 };

for (int i = 0; i < n.length; i++) {
for (int j = n.length - 1; j > i; j--)
if (n[j] < n[j - 1]) {
int x = n[j - 1];
n[j - 1] = n[j];
n[j] = x;

}
}
for (int i = 0; i < n.length; i++) {
System.out.print(n[i] + " ");
}
}
}

当处理到数组中最后一个元素的时候,n[i+1]超出数组大小了

根本运行不了

因为你n[i+1]超出数值下标范围,当i=6的时候就存在n[7],自己在体会体会。

如果你是想排序的话,还的要加一层循环的,这是冒泡的问题,可以到网上看看
我按着你的意思,写了下
public class Paixu {
public static void main(String[] args){
int[] n= {13,11,21,45,20,15,1};
for(int j=0;j<n.length;j++){
for (int i = 0; i < n.