代码之家  ›  专栏  ›  技术社区  ›  user225269

Java中从最高到最低的冒泡

  •  2
  • user225269  · 技术社区  · 15 年前

    我正在寻找一个Java中的BuffelRoT代码,这与我在网上搜索时看到的通常情况相反。 我不太明白下面的代码,我只知道它从最低到最高对一堆数字进行排序。下面的代码是否可修改,以便不从最低到最高输出数字。它输出最高到最低?

    int i;
        int array[] = {12,9,4,99,120,1,3,10};
        System.out.println("Values Before the sort:\n");
        for(i = 0; i < array.length; i++)
          System.out.print( array[i]+"  ");
        System.out.println();
        bubble_srt(array, array.length);
        System.out.print("Values after the sort:\n");
        for(i = 0; i <array.length; i++)
          System.out.print(array[i]+"  ");
        System.out.println();
        System.out.println("PAUSE");
      }
    
      public static void bubble_srt( int a[], int n ){
        int i, j,t=0;
        for(i = 0; i < n; i++){
          for(j = 1; j < (n-i); j++){
            if(a[j-1] > a[j]){
              t = a[j-1];
              a[j-1]=a[j];
              a[j]=t;
            }
          }
        }
      }
    
    4 回复  |  直到 14 年前
        1
  •  3
  •   Patrick McDonald    15 年前

    if(a[j-1] > a[j]){
    

    if(a[j-1] < a[j]){
    
        2
  •  2
  •   oezi    15 年前

        3
  •  1
  •   Woot4Moo    15 年前

        4
  •  1
  •   user unknown    14 年前

    public void swap (int i, int j, int [] arr) {
        int tmp = arr [i];
        arr [i] = arr [j];
        arr [j] = tmp;
    }
    

    public static void bubbleSort (int a[], int n) {
        for (int i = 0; i < n; i++) {
            for (int j = 1; j < (n-i); j++) {
                if (a[j-1] > a[j]) {
                    swap (j, j-1, a);
                }
            }
        }
    }
    
        // ... missing ...
    

    public static void show (int [] arr)
    {
        for (int i : arr) 
            System.out.print (i + " ");
        System.out.println ();
    }
    

        int array[] = {12, 9, 4, 99, 120, 1, 3, 10};
        System.out.println ("Values Before the sort:\n");
        show (array);
        bubbleSort (array, array.length);
        System.out.print ("Values after the sort:\n");
        show (array);
        System.out.println ("PAUSE");
    }
    

    if (a[j-1] > a[j]) {
    

    if (a[j-1] < a[j]) {