Bubble Sort in Java Program
Here you will get example code of Bubble Sort in Java using scanner class.
Bubble Sort is a basic sorting algorithms that works in the list continually, compares adjacent elements, and swaps them if they are not in order. This procedure is repeated until the full list has been sorted.
Bubble Sort Algorithm
1 2 3 4 5 6 7 8 9 10 11 12 13 | for (int i = 0; i < num - 1; i++) { for (int j = 0; j < num - i - 1; j++) { if (arr[j] > arr[j + 1]) { // Swapping int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } |
Here, num is the number of elements.
Bubble Sort in Java Program
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | import java.util.*; public class BubbleSort { public static void main(String[] args) { Scanner sc = new Scanner(System.in); //Input number of elements System.out.print("Enter number of elements : "); int num=sc.nextInt(); int i,j; int arr[]=new int[num]; // input Array elements System.out.print("Enter elements of array : "); for (i = 0; i < arr.length; i++) { arr[i] = sc.nextInt(); } // sorting with bubble sort for (i = 0; i < arr.length-1; i++) { for (j = 0; j < arr.length-1-i; j++) { if (arr[j] > arr[j+1]) { int temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; } } } //print sorted array for (i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } } } |
Output
Check out our other Java Programming Examples