Reputation: 10913
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;
}
}
}
}
Upvotes: 2
Views: 7783
Reputation: 36229
Some words about your code:
If you move the swap-method out of your inner loop, it get's more readable, and more easy to reason about the independent parts.
public void swap (int i, int j, int [] arr) {
int tmp = arr [i];
arr [i] = arr [j];
arr [j] = tmp;
}
Sweet little methods are easy to understand and test, which is important.
Don't declare the index variables outside the for. This makes it harder to reason about your code - the variables are visible without necessity outside the loop. In the old code, you gain nothing from declaring tmp outside of the inner loop. Declaration is cost-free at runtime.
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 ...
Don't repeat yourself. Move duplicated code into a method.
public static void show (int [] arr)
{
for (int i : arr)
System.out.print (i + " ");
System.out.println ();
}
Sweet little methods are easy to test. Use the simplified for-loop, whenever possible, to avoid off-by-one-errors, and to be more robust to code changes - they work for Lists too, for example.
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");
}
With the simplified code, it get's more easy to reason about, what which part does.
if (a[j-1] > a[j]) {
needs just to be changed
if (a[j-1] < a[j]) {
to reverse the order.
Upvotes: 3
Reputation: 51807
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.
Upvotes: 2
Reputation: 24326
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
Upvotes: 1