Java Tutorial
Bubble sort is repeatedly comparing pairs of adjacent elements and then swapping their positions if they exist in the wrong order.
Bubble sorting can be used for collections of numbers, strings, characters etc.
The basic idea behind bubble sort is to imagine that the records to be sorted are kept in an array held vertically. The records with lower key values are 'light' and bubble up to the top. We make repeated iteration over the array from bottom to top.
import java.util.Scanner; public class BubbleSortingTest { public static void bubbleSort(int[] numberList){ int temp = 0; for (int k=0;k<numberList.length-1;k++){ for(int i=0; i<(numberList.length-k-1);i++){ if (numberList[i] > numberList[i+1]){ // Swapping of positions if not in sorted order temp = numberList[i]; numberList[i] = numberList[i+1]; numberList[i+1] = temp; } } } } public static void main(String[] args){ int[] numberList; Scanner in = new Scanner(System.in); System.out.println("Enter numbers count: "); int count = in.nextInt(); numberList = new int[count]; System.out.println("Enter numbers: "); for (int i=0;i<count;i++){ numberList[i]=in.nextInt(); } in.close(); bubbleSort(numberList); System.out.println("Sorted numbers: "); for(int number : numberList){ System.out.print(number+"\t"); } } }Output:
$ javac BubbleSortingTest.java $ java BubbleSortingTest Enter numbers count: 5 Enter numbers: 4 5 1 8 2 Sorted numbers: 1 2 4 5 8
Java Tutorial
Privacy Policy | Copyright2020 - All Rights Reserved. | Contact us | Report website issues in Github | Facebook page | Google+ page