简体   繁体   中英

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 .

Change the if condition to:

...
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...

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

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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