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));

        // 排序后:

        System.out.println(Arrays.toString(ns));

        int low =0,high=ns.length-1;

        boolean flag=true;

        while(low<high&&flag) {

        	flag=false;

        	for(int i=low;i<high;i++) {

        		if(ns[i]<ns[i+1]) {

        			int tmp=ns[i+1];

        			ns[i+1]=ns[i];

        			ns[i]=tmp;

        			flag=true;

        		}

        	}

        	high--;

        	for(int i=high;i>low;i--) {

        		if(ns[i]>ns[i-1]) {

        			int tmp = ns[i];

        			ns[i]=ns[i-1];

        			ns[i-1]=tmp;

        			flag=true;

        		}

        	}

        	low++;

        }

        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