This is a Java program that performs sorting of elements using bubble sort. Bubble sort is a technique where each element is compared with its adjacent element , if its adjacent element is smaller then swapping occurs, this continues until every element is checked. |
See the animation below to understand,
"Bubble-sort-example" by Swfung8 - Own work. Licensed under CC BY-SA 3.0 via Wikimedia Commons.
PROGRAM :
package codingcorner.in; import java.util.Scanner; public class BubbleSort { public static void main(String[] args) { int n, i, j, swap; int[] array = new int[100]; Scanner scan = new Scanner(System.in); System.out.print("How many Elements ? \t"); n = scan.nextInt(); for (i = 0; i < n; i++) { System.out.print("Enter number" + (i + 1)); array[i] = scan.nextInt(); } scan.close(); for (i = 0; i < (n - 1); i++) { for (j = 0; j < n - i - 1; j++) { if (array[j] > array[j + 1]) { swap = array[j]; array[j] = array[j + 1]; array[j + 1] = swap; } } } System.out.print("\nSorted list :\n"); for (i = 0; i < n; i++) System.out.print(array[i] + "\t"); } }
OUTPUT :