繁体   English   中英

bubbles中从最高到最低的数字

[英]bubblesort from highest to lowest number in java

我正在寻找java中的bubblesort代码,这与我在网上搜索时常见的东西相反。 我真的不明白下面的代码,我所知道的是它将一堆数字从最低到最高排序。 下面的代码是否可以修改,以便输出从最低到最高的数字。 它输出从最高到最低?

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

更改

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

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

您可以更改bubblesort以满足您的需要或保持原样并向后移动已排序的数组。 对于两者,你应该尝试理解这么一小段代码而不是简单地要求修改代码。

关于你的代码的一些话:

如果将swap-method移出内循环,它会更易读,并且更容易推理独立部分。

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

甜蜜的小方法很容易理解和测试,这很重要。

不要在for之外声明索引变量。 这使得你的代码更难以推理 - 变量在循环外无需可见。 在旧代码中,从内循环外部声明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 ();
}

甜蜜的小方法很容易测试。 尽可能使用简化的for循环来避免逐个错误,并且对代码更改更加健壮 - 例如,它们也适用于列表。

    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]) {

扭转秩序。

for(i = array.length -1; i >=0; i--)
{
System.out.println(array[i]);
}

应该管用。 你从数组的末尾开始然后向后移动

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM