Bubble Sort Example in Java

class BubbleSortExample {
	public static void main(String[] args) {

		int array[] = { 10, 4, 2, 11, 56, 34, 11, 0, 7 };
		int n = array.length;
		
		System.out.println("Before Sorting: ");
		for (int i = 0; i < n; i++) {
			System.out.print(array[i] + " , ");
		}

		int tmp;
		for (int i = 0; i < (n - 1); i++) {
			for (int j = 0; j < n - i - 1; j++) {
				if (array[j] > array[j + 1]) {
					tmp = array[j];
					array[j] = array[j + 1];
					array[j + 1] = tmp;
				}
			}
		}

		System.out.println("\nAfter Sorting: ");

		for (int i = 0; i < n; i++) {
			System.out.print(array[i] + " , ");
		}
	}
}
Output
Before Sorting: 10 , 4 , 2 , 11 , 56 , 34 , 11 , 0 , 7 , After Sorting: 0 , 2 , 4 , 7 , 10 , 11 , 11 , 34 , 56 ,


















Receive Latest Java Examples in Your Email: