1. 程式人生 > >氣泡排序--對陣列中的元素進行降序排列

氣泡排序--對陣列中的元素進行降序排列

核心程式碼:

for (int i = 0;i < array.length;i++){
    for(int j = i;j < array.length;j++){
        if (array[i] < array[j]){
            int temp = array[i];
            array[i] = array[j];
            array[i] = temp;
        }
    }
}

text

import java.util.Random;
class lijia
{
     int x [] = new
int[100]; Random r = new Random(); public void getGrade() { for(int i = 0;i< x.length;i++) { x [i] = r.nextInt(100); System.out.print(x[i]+" ") ; } } public double ave() { double sum = 0 ; for(int i =0;i<x.length;i++) { sum = sum + x[i]; } return
sum/100; } public int max() { int max = x[0]; for(int i = 0;i<x.length;i++) { if(x[i]>max) max = x[i]; } return max; } public void order() { int index; for(int i = 0;i<x.length;i++) for
(int j = i+1;j<x.length;j++) { if(x[j]>x[i]) { index = x[i] ; x[i] = x[j] ; x[j] = index; } } for(int i = 0;i<x.length;i++) { System.out.print(x[i]+" "); } } } class sy { public static void main(String []args) { lijia g = new lijia(); System.out.println("獲取的一百個成績:"); g.getGrade(); System.out.println(); System.out.println("平均分為 :"); System.out.println(g.ave()); System.out.println("最高分為:"); System.out.println(g.max()); System.out.println("排序後的結果:"); g.order(); System.out.println( ); } }