In java program for bubble sort there is checking of all numbers user entered. After that we use an array to store. Java bubble sort is the simplest way to sort the numbers in ascending order. Bubble sort java code is simple to understand. Bubble sort program in java is same as that of sorting logic in c and c++. Bubble sort java contains the logic of swapping due to that java program for bubble sort is easy and time efficient.
The following java bubble sort example is only basis of for loop logic. In the below bubble sort java code use only this “<” sign descending order in the if loop.
Program for Bubble Sort java code
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 |
import java.util.Scanner; // java bubble sort example class BubbleSort { public static void main(String []args) { int i, j, k, swap; Scanner in = new Scanner(System.in); System.out.println("Input number of integers to sort"); i = in.nextInt(); int array[] = new int[i]; System.out.println("Enter " + i + " integers"); for (j = 0; j < i; j++) // logic of java bubble sort array[j] = in.nextInt(); for (j = 0; j < ( i - 1 ); j++) { for (k = 0; k < i - j - 1; k++) { if (array[k] > array[k+1]) // For descending order use ” < “ { swap = array[k]; array[k] = array[k+1]; array[k+1] = swap; } } } System.out.println("Sorted list of numbers"); for (j = 0; j < i; j++) System.out.println(array[j]); } } // End of example bubble sort program in java. |