Sorting Algorithms

Java Bubble Sort Descending Order Example

Want to learn quickly?
Try one of the many quizzes. More than Java 400 questions with detailed answers.

8 Comments

  • Thanks for taking the time to post this example. I have used it but I find that the last element is not getting sorted:
    int[] sortArray = new int[]{3, 5, 1, 6, 8, 2, 7, 12, 10, 9};
    for(int i=0; i<sortarray.length; i++){=”” for(int=”” j=”1;” j<(sortarray.length-1);=”” j++){=”” if(sortarray[j-1]=”” <=”” sortarray[j]){=”” int=”” temp=”sortArray[j-1];” sortarray[j-1]=”sortArray[j];” sortarray[j]=”temp;” }=”” }=”” }=”” this=”” produces=”” the=”” following:=”” [12,=”” 10,=”” 8,=”” 7,=”” 6,=”” 5,=”” 3,=”” 2,=”” 1,=”” 9]=””>

  • I had been trying to reverse my array to descending order for literally 20 hours until I came across your example!! very useful…Thanx again

  • To check the last element or complete loop, I think The J loop must have (j <n) rather=”” then=”” (j=”” <=”” n-1).=”” enjoy=”” coding=”” br=”” mohammed=”” nadeem=”” bari=”” write2nadeem(at)live.com=””>

  • Thanks for taking the time to post this example 🙂

    I have done (for fun, i like programming) the same example here :

    public class triTab {

    public static void trier(int intArray[]){

    for(int z = 0; z<intarray.length;z++){ for(int=”” i=”0;(intArray.length-1)”>i;i++){

    if(intArray[i]>intArray[i+1]){

    int tempon= intArray[i+1];

    intArray[i+1]=intArray[i];

    intArray[i]=tempon;

    }

    }

    }

    }

    public static void afficher(int tableauTrier [] ){

    int i=0;

    while(i<(tableauTrier.length)){

    System.out.println(tableauTrier[i]);

    i++;

    }

    }

    /**

    * @author Florian Brunet

    * @country France

    * @param args

    */

    public static void main(String[] args) {

    int tableauATrier [] ;//= new int[2];

    tableauATrier=new int[]{6,2,4,1,5,888,10,3};

    System.out.println(“tableauATrier”);

    afficher(tableauATrier);

    System.out.println(“fin”);

    trier(tableauATrier);

    System.out.println(“tableauTrier”);

    afficher(tableauATrier);

    }

    }

Sponsors

Facebook Fans