1. 程式人生 > >Java:氣泡排序

Java:氣泡排序

氣泡排序: 

package com.wochat.controller;

public class MainClass {
    public static void main(String[] args) {

        int score[] = {67, 75, 69, 88};

        for (int i = 0; i < score.length - 1; i++){
            for (int j = 0; j < score.length - 1 - i; j++){
                if (score[j] > score[j + 1]){
                    int temp = score[j];
                    score[j] = score[j + 1];
                    score[j + 1] = temp;
                }
            }
        }
        for (int i : score) {
            System.out.println(i);
        }

    }
}

 if (score[j] > score[j + 1]){   升序

if (score[j] < score[j + 1]){   降序
 

 

int[] score = {67, 75, 69, 88};

        Arrays.sort(score);

        for (int i : score) {
            System.out.println(i);
        }

預設升序

 

package com.wochat.controller;

import java.util.Arrays;

public class MainClass {
    public static void main(String[] args) {

        int[] score = {67, 75, 69, 88};

        Arrays.sort(score);
        for (int i = score.length - 1; i >= 0; i--) {
            System.out.println(score[i]);
        }


    }
}

反之,則是降序

 

package com.wochat.controller;


import java.util.Arrays;

public class MainClass {
    public static void main(String[] args) {


        int[] score = {67, 75, 69, 88};
        int[] ints=new int[score.length];

        Arrays.sort(score);
        int v=0;
        for (int i = score.length - 1; i >= 0; i--) {
            ints[v]=score[i];
            v++;
        }

        for (int anInt : ints) {
            System.out.println(anInt);
        }

    }
}