Java Bubble Sort Descending Order - Java Data Structure

Java examples for Data Structure:Sort

Introduction

Bubble sort traverses the array from first to array_length - 1 position and compare the element with the next one.

Element is swapped with the next element if the next element is smaller.

Demo Code

 
public class Main {

  public static void main(String[] args) {
    int intArray[] = new int[] { 1, 9, 5, 4, 0, 31 };
    System.out.println("Array Before Bubble Sort");
    for (int i = 0; i < intArray.length; i++) {
      System.out.print(intArray[i] + " ");
    }/* w  w  w. java2s  .  co  m*/
    bubbleSort(intArray);
    System.out.println("");
    System.out.println("Array After Bubble Sort");
    for (int i = 0; i < intArray.length; i++) {
      System.out.print(intArray[i] + " ");
    }
  }
  private static void bubbleSort(int[] intArray) {
    int n = intArray.length;
    int temp = 0;
    for (int i = 0; i < n; i++) {
      for (int j = 1; j < (n - i); j++) {
        if (intArray[j - 1] < intArray[j]) {
          // swap the elements!
          temp = intArray[j - 1];
          intArray[j - 1] = intArray[j];
          intArray[j] = temp;
        }
      }
    }
  }
}

Related Tutorials