Discuss / Java / 冒泡排序优化

冒泡排序优化

Topic source
import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[] ns = { 28, 12, 89, 73, 65, 18, 96, 50, 8, 36 };
        // 排序前:
        System.out.println(Arrays.toString(ns));
        
        int len = ns.length-1;
        int temp = 0; 
        int tempPostion = 0;
        for (int i = 0; i < ns.length-1; i++) {
            int flag = 1; 
            for (int j = 0; j < len; j++) {
                if (ns[j] < ns[j+1]) {
                    temp = ns[j+1];
                    ns[j+1] = ns[j];
                    ns[j] = temp;
                    flag = 0; 
                    tempPostion = j; 
                }
            }
            len = tempPostion; 
            if (flag == 1) {
                break;}
        }
           
        // 排序后:
        System.out.println(Arrays.toString(ns));
        if (Arrays.toString(ns).equals("[96, 89, 73, 65, 50, 36, 28, 18, 12, 8]")) {
            System.out.println("测试成功");
        } else {
            System.out.println("测试失败");
        }
    }
}

  • 1

Reply