随笔-生活工作点滴

Java 数组冒泡排序

2019-07-04  本文已影响0人  勇者与王者
import java.util.Scanner;


public class ex7_18 {
    public static void main(String [] args){
        Scanner in = new Scanner(System.in);
        System.out.println("Enter ten numbers: ");
        double [] list = new double[10];
        for (int i = 0 ; i<list.length;i++){
            list[i] = in.nextDouble();
        }
        bubbleSort(list);
        for (double i : list){
            System.out.print(i+" ");
        }

        
    }
    
    public static void bubbleSort(double [] list){
        double temp = 0;
        
        for (int n = 0 ; n<list.length;n++){
            for (int i = 0 ; i< list.length-1;i++){
                if (list[i]>list[i+1]){
                    temp = list[i];
                    list[i] = list[i+1];
                    list[i+1] = temp;
                }
            }
        }
            
    }
    
}

想了半天怎么才算冒泡,得交换相邻元素的值,然后这个索引还得一直递增到 length -1 ,最后两个for 循环搞定

上一篇下一篇

猜你喜欢

热点阅读