English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this example, we will learn to perform bubble sort algorithm in Java.
Before learning the bubble sort algorithm in Java, make sure you understand the working principle of the bubble sort algorithm.
//Import classes import java.util.Arrays; import java.util.Scanner; class Main { //Create a scanner object. //Accept user input Scanner input = new Scanner(System.in); //The method to perform bubble sort void bubbleSort(int array[]) { int size = array.length; //Used for ascending or descending order sorting System.out.println("Choose the sorting order:"); System.out.println("1Represents ascending order \n2Represents descending order "); int sortOrder = input.nextInt(); //Run the loop twice //The first loop visits each element of the array for (int i = 0; i < size - 1; i++) //The second loop performs comparisons in each iteration for (int j = 0; j < size - i - 1; j++) //Sort the array in ascending order if (sortOrder == 1]) { //Compare adjacent elements if (array[j] > array[j + 1]) { // If the left element is greater than the right, then swap int temp = array[j]; array[j] = array[j + 1]; array[j + 1]=temp; } } //Sort the array in descending order else { // Compare adjacent elements if (array[j] < array[j + 1]) { //If the left element is less than the right, then swap int temp = array[j]; array[j] = array[j + 1]; array[j + 1]=temp; } } } //main method public static void main(String args[]) { //Create an array int[] data = { -2, 45, 0, 11, -9 }; //Create an object of Main class Main bs = new Main(); //Call method bubbleSort using object bs //Pass the array as a method parameter bs.bubbleSort(data); System.out.println("Array sorted in ascending order:"); //Call Arrays class toString() //Convert data to a string System.out.println(Arrays.toString(data)); } }
Output 1
Select sorting order: 1 represents ascending order 2 represents descending order 1 Sorted array: [-9, -2, 0, 11, 45]
In this case, we input 1. Therefore, the program sorts the array in ascending order.
Output 2
Select sorting order: 1 represents ascending order 2 represents descending order 2 Sorted array: [45, 11, 0, -2, -9]
In this case, we input 2 . Therefore, the program sorts the array in descending order.
NoteWe have already usedJava Scanner ClassGet input from the user.