views:

88

answers:

3

I'm looking for a bubblesort code in java that is opposite of the usual thing that I'm seeing when I search the internet. I don't really understand the code below, all I know is that it sorts a bunch of numbers from lowest to highest. Is the code below modifiable so that instead of outputting the numbers from lowest to highest. It outputs it as highest to lowest?

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;
        }
      }
    }
  }
+3  A: 

change

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

to

if(a[j-1] < a[j]){
Patrick McDonald
wouldn't that be a '<=' instead of '<'?
Sagar V
you wouldnt need to switch if the value is =
Woot4Moo
oh yeah! Sorry for that :)
Sagar V
+1  A: 

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

Should work. You start at the end of the array and go backwards

Woot4Moo
shouldn't that be for(i = array.length - 1; i >=0; i--)?
Patrick McDonald
oops forgot the zero index for a second... thanks
Woot4Moo
+2  A: 

you could change the bubblesort to satisfy your needs or leave it as is and walk the sorted array backwards. for both, you should try to understand such a little piece of code instead of simply asking for the modified code.

oezi
+10 if I could!
teedyay