第一種方法:
public class Demo01 {
public static void main(String[] args) {
int a[] = { 2, 3,77, 6, 4, 0, 1, 7, 8, 5, 9 };
//調用
sort(a);
}
public static void toString(int[] a) {
for (int i = 0; i < a.length; i++) {
System.out.println(a[i]);
}
}
private static void sort(int[] a) {
int length = a.length;
//定義一個零時變量
int temp = 0;
for (int j = 0; j < a.length - 1; j++) {
for (int i = 0; i < a.length - 1 - j; i++) {
if (a[i] < a[i + 1]) {
// 交換
temp = a[i + 1];
a[i + 1] = a[i];
a[i] = temp;
}
}
}
toString(a);
}
}
第二種方法:
public class Demo01 {
public static void main(String[] args) {
//冒泡排序算法
int[] numbers=new int[]{1,5,8,2,3,9,4};
int i,j;
for(i=0;i<numbers.length-1;i++)
{
for(j=0;j<numbers.length-1-i;j++)
{
if(numbers[j]>numbers[j+1])
{
int temp=numbers[j];
numbers[j]=numbers[j+1];
numbers[j+1]=temp;
}
}
}
System.out.println("從小到大排序後的結果是:");
for(i=0;i<numbers.length;i++)
System.out.print(numbers[i]+" ");
}
}