Showing posts with label Bubble sort. Show all posts
Showing posts with label Bubble sort. Show all posts

Bubble sort in Java

Bubble sort in java

Bubble sort is the simple sorting algorithm and same time has worst-case and average complexity. Bubble sort iterating down from first element to the last element in the array by comparing each pair of elements and switching elements if they meets our sorting condition. So lets see simple example in Java by using Bubble sort algorithm.



public class BubbleSort {

 public static void main(String[] args) {

  int values[] = { 5, 4, 8, 6, 9, 1, 7, 3, 2 };

  System.out.print("\nBefore sort : ");
  printArray(values);

  bubbleSort(values);

  System.out.print("\nAfter sort : ");
  printArray(values);
 }

 private static void bubbleSort(int[] array) {
  for (int i = 0; i < array.length - 1; i++) {
   for (int j = i + 1; j < array.length; j++) {
    if (array[i] > array[j]) {
     int tmp = array[i];
     array[i] = array[j];
     array[j] = tmp;
    }
   }
  }
 }

 private static void printArray(int[] array) {
  for (int i = 0; i < array.length; i++) {
   System.out.print(array[i] + ", ");
  }
 }
}


OUTPUT:


Before sort : 5, 4, 8, 6, 9, 1, 7, 3, 2, 
After sort : 1, 2, 3, 4, 5, 6, 7, 8, 9,