数组元素升序与降序排列(三种方式)

    技术2022-07-14  58

    public class Test13 { public static void main(String[] args) { bubbleSort(); } public static int[] bubbleSort(int[] a) { int[] a = {23,45,67,453,43,13,1}; int temp; for(int i = 0; i < a.length - 1; i++) { for(int j = 0; j < a.length - 1; j++) { if(a[j] > a[j + 1]) { temp = a[j]; a[j] = a[j + 1]; a[j + 1] = temp; } } } for(int i = 0; i < a.length; i++) { System.out.println(a[i]); } } } public class TestJDKSort { public static void main(String[] args) { int[] a = {7,4,5,6,2}; java.util.Arrays.sort(a);//仅支持升序 //手工完成倒置 for(int i = 0; i < a.length / 2; i++) { //完成首尾两值交换 int temp = a[i]; a[i] = a[a.length - 1 - i] ; a[a.length - 1 -i] = temp; } for(int i = 0; i < a.length; i++) { System.out.print(a[i] + "\t"); } } } public class Test14 { public static void main(String[] args) { int[] a = {123,34,23,56,433, 897,455,36,6,8}; int temp = 0; for(int i = 0; i < a.length - 1; i++) { for(int j = 0;j < a.length - 1 - i; j++) { if(a[j] > a[j+1]) {//升序大于(降序大于改为小于即可) temp = a[j]; a[j] = a[j+1]; a[j+1] = temp; } } } for(int i = 0; i < a.length; i++) { System.out.println(a[i]); } } }
    Processed: 0.024, SQL: 9