Exercise:
Write a Java Program to implement Bubble Sort algorithm.
Click Here to View the Solution!
import java.util.Arrays;
import java.util.Scanner;
public class BubbleSort {
// create a scanner class object to take input
Scanner input =
new Scanner(System.in);
// method to perform bubble sort
void bubbleSort(int array[]) {
int size = array.length;
// Select preference
System.out.println(
"Choose Sorting Order:");
System.out.println(
"Enter 1 for Ascending \n Eneter 2 for Descending");
int sortOrder = input.nextInt();
// first loop access each element of the array
for (
int i =
0; i < size -
1; i++)
// second loop performs the comparison in each iteration
for (
int j =
0; j < size - i -
1; j++)
// Sorting in ascending order
if (sortOrder ==
1) {
// compares the adjacent elements
if (array[j] > array[j +
1]) {
// swap places if left element is bigger than right
int temp = array[j];
array[j] = array[j +
1];
array[j +
1] = temp;
}
}
// Sorting in descending order
else {
if (array[j] < array[j +
1]) {
// swap places if left element is smaller than the right one
int temp = array[j];
array[j] = array[j +
1];
array[j +
1] = temp;
}
}
}
public static void main(String args[]) {
int[] data = { 78,90,-34,9,87,-27,99,-12,0,56,-999};
// creating object of Main class named bs
BubbleSort bs =
new BubbleSort();
// call the method bubbleSort using object bs()
bs.bubbleSort(data);
System.out.println(
"Sorted Array:");
// display data of array in string
System.out.println(Arrays.toString(data));
}
}
Click Here to View the Output!
Choose Sorting Order: Enter 1 for Ascending Eneter 2 for Descending 1 Sorted Array: [-999, -34, -27, -12, 0, 9, 56, 78, 87, 90, 99] 2 Sorted Array: [99, 90, 87, 78, 56, 9, 0, -12, -27, -34, -999]
Click Here to View the Explanation!
- For output 1:
- Here we have chosen option 1 as input and thus our output comes in the form of an array sorted in ascending order.
- For output 2:
- Here we have chosen option 2 as input and thus our output comes in the form of an array sorted in descending order.
- For the purpose of retrieving user input, Java Scanner class has been used here.