簡單的陣列排序
阿新 • • 發佈:2018-11-30
1.小到大
@org.junit.Test
public void test() throws InterruptedException {
int[] num={1,6,5,2,7};
for (int i=0;i<num.length-1;i++) {
for (int j = 0; j <num.length-1; j++) {
int b = 0;
if (num[j]>num[j+1]){
b = num[j];
num[j] = num[j + 1];
num[j+ 1] = b;
}
}
}
for (int i=0;i<num.length;i++){
System.out.println(num[i]);
}
}
2.大到小
@org.junit.Test
public void test() throws InterruptedException {
int[] num={1,6,5,2,7};
for (int i=0;i<num.length-1;i++) {
for (int j = 0; j <num.length-1; j++) {
int b = 0;
if (num[j]<num[j+1]){ //這裡不一樣
b = num[j];
num[j] = num[j + 1];
num[j+ 1] = b;
}
}
}
for (int i=0;i<num.length;i++){
System.out.println(num[i]);
}
}