简体   繁体   English

在Java中对气泡进行排序(递归)整数数组时遇到问题

[英]Trouble bubble sorting (recursion) an array of integers in Java

Attempting to implement a recursive method to sort an array of integers: 尝试实现一种递归方法来对整数数组进行排序:

    public static void bubbleSort(int[] arr, int n){

      int index = n-1;

      System.out.println("Round number: " + n);
      System.out.println(Arrays.toString(arr));

      while(index>=1)
      {
          if(arr[index] <  arr[index-1])
              swap(arr, index, index-1);


          index--;
      }
      if(n>1)
          bubbleSort(arr, n-1);
  }

} }

It seems to work fine for the first few rounds, moving the smallest integer in the set to the front, but it just stops working around midway. 它似乎在前几轮中工作良好,将集合中的最小整数移到了前面,但是它只是在中途停止工作。 Any idea why? 知道为什么吗? Thanks! 谢谢!

Your algorithm moves the smallest value to the start of the array each time, then ignores the last element on subsequent calls. 您的算法每次都会将最小值移到数组的开头,然后忽略后续调用中的最后一个元素。 Unfortunately the last element isn't guaranteed to be the largest. 不幸的是,最后的元素并不能保证最大。

One way to fix it might be to initialise index to arr.length - 1 , and continue the loop while index > arr.length - n . 解决该问题的一种方法可能是将index初始化为arr.length - 1 ,并在index > arr.length - n时继续循环。

Change the if condition to: if条件更改为:

...
if(arr[index] <  arr[index-1]){
   swap(arr, index, index-1);
   index = n;
}
index--;
...

The problem is that after you find an array member to "delegate" across the array - you need to "restart" cause there could be other members that needs to be "reconsidered". 问题是,在找到要在整个阵列中“委派”的阵列成员之后,您需要“重新启动”,因为可能需要“重新考虑”其他成员。 Run with a debugger and see what I mean if I'm not clear enough with my description. 使用调试器运行,看看我对我的描述不够清楚的意思。

Full solution: 完整解决方案:

import java.util.Arrays;

/**
 * User: alfasin
 * Date: 8/5/13
 */
public class BubbleSort {

    public static void bubbleSort(int[] arr, int n){

        int index = n-1;

        System.out.println("Round number: " + n);
        System.out.println(Arrays.toString(arr));

        while(index>=1)
        {
            if(arr[index] <  arr[index-1]){
                swap(arr, index, index-1);
                index = n;
            }
            index--;
        }
        if(n>1)
            bubbleSort(arr, n-1);
    }

    private static void swap(int[] arr, int index, int i) {
        arr[i] = arr[i] ^ arr[index];
        arr[index] = arr[i] ^ arr[index];
        arr[i] = arr[i] ^ arr[index];
    }

    public static void main(String...args){
        int[] arr = {4,2,9,6,2,8,1};
        bubbleSort(arr, arr.length);
        for(int i=0; i<arr.length; i++){
            System.out.print(arr[i]+" ");
        }
    }

}

Like sjee397 suggested - this is more of a "version" of bubble sort... 就像sjee397建议的一样-这更像是气泡排序的“版本” ...

A more "conservative" version of bubble sort: 冒泡排序的一个更“保守”的版本:

public static void bubbleSort(int[] arr, int n){
        boolean swapped= true;
        while (swapped){
            swapped = false;
            for(int i=0; i<arr.length-1; i++){
                if(arr[i]>arr[i+1]){
                    swap(arr,i,i+1);
                    swapped = true;
                }
            }
        }
    }

Try this: 尝试这个:

import java.util.*;

public class Test{
    public static void main(String[] args){
        int[] ttt = {9,8,7,6,5,4,3,2,1};

        bubbleSort(ttt, ttt.length);
    }

    public static void bubbleSort(int[] arr, int n){
        int index = 0;

        System.out.println("Round number: " + n);
        System.out.println(Arrays.toString(arr));

        while(index < n - 1){
            if(arr[index] >  arr[index + 1]){
                swap(arr, index, index + 1);
            }
            index++;
        }

        if(n > 1){
            bubbleSort(arr, n-1);
        }
    }

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

In your case on every round you guarantee that by the end of every round you will have the smallest number pushed to its place, but then leave out the last element of an array, which is not necessarily the largest number. 就您在每一轮中的情况而言,您可以确保在每一轮结束时将最小的数字推入其位置,但随后忽略数组的最后一个元素,不一定是最大的数字。 You should do it in reverse order, push the largest number to its place and then leave it out in the next round. 您应该按相反的顺序进行操作,将最大的数字推到其位置,然后在下一轮中将其忽略。

http://en.wikipedia.org/wiki/File:Bubble-sort-example-300px.gif http://en.wikipedia.org/wiki/File:Bubble-sort-example-300px.gif

FYI: Bubble sort's worst case performance is O(n^2), maybe you'd want to implement better sort algorithms like quicksort or merge sort? 仅供参考:冒泡排序的最坏情况是O(n ^ 2),也许您想实现更好的排序算法,例如快速排序或合并排序?

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

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