# Java program to implement bubble sort

Java Programming Java8Java Technologies

Bubble sort is a simple sorting algorithm. This sorting algorithm is a comparison-based algorithm in which each pair of adjacent elements is compared and the elements are swapped if they are not in order. This algorithm is not suitable for large datasets as its average and worst case complexity is of Ο(n2) where n is the number of items.

## Example

Live Demo

public class BubbleSort {
static void bubbleSort(int[] arr) {
int n = arr.length;
int temp = 0;

for(int i = 0; i < n; i++) {
for(int j=1; j < (n-i); j++) {
if(arr[j-1] > arr[j]) {
temp = arr[j-1];
arr[j-1] = arr[j];
arr[j] = temp;
}
}
}
}
public static void main(String[] args) {
int arr[] = { 2, 5, -2, 6, -3, 8, 0, -7, -9, 4 };
System.out.println("Array Before Bubble Sort");

for(int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
bubbleSort(arr);
System.out.println("Array After Bubble Sort");

for(int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
}

## Output

Array Before Bubble Sort
2 5 -2 6 -3 8 0 -7 -9 4
Array After Bubble Sort
-9 -7 -3 -2 0 2 4 5 6 8
Published on 25-Apr-2018 07:18:57