Latest :

Implement Bubble Sort Java – Algorithm | 2 Easy Ways

Bubble Sort in Java – We will discuss the different methods to Implement Bubble Sort in 2 Simple ways. The compiler has been added so that you easily execute the programs yourself, alongside suitable examples and sample outputs added to implement bubble sort – List of all sorting Programs In Java

  • Program – Using Array.
  • Program – Using Buffered Reader.

Bubble Sort Java Algorithm – Using Array

Output:

Explanation For Above Program:

1) For bubble sort, we are using array concept.

2) Printarray() method prints the array elements, sort() method will sort the array elements using bubble sort logic.

3) For each iteration of i, the inner loop compare the adjacent numbers and moves the large number towards the right and the large number will be placed in the proper position.

4) The given series is 5, 4, 3, 2, 1.

For the first iteration of i

a) The inner loop will compare 5,4. 5 is the large number compared with 4, so 5 shifted to the right. Now the series is 4, 5, 3, 2, 1.

b) Compare 5 with 3 and shift 5 to right. The series is 4, 3, 5, 2, 1.

c) Compare 5 with 2 and shift 5 to right. The series is 4, 3, 2, 5, 1.

d) Compare 5 with 1 and shift 5 to right. The series is 4, 3, 2, 1, 5.

After 1st iteration, 5 will be shifted to the last index. Now the series is 4, 3, 2, 1, 5.

For the 2nd iteration of i

a) The inner loop compares 4,3 and shift 4 to right. The series is 3, 4, 2, 1, 5.

b) Compare 4,2 and shift 4 to right, series is 3, 2, 4, 1, 5.

c) Compare 4,1 and shift 4 to right, series is 3, 2, 1, 4, 5.

For the 3rd iteration of i

a) The inner loop will compare 3,2 and shift the number 3 to right, series is 2, 3, 1, 4, 5.

b) Compare 3 with 1 ,shift 3 to right, series is 2, 1, 3, 4, 5.

For 4th iteration

a) Inner loop compares 2,1 and shifts 2 to right, the series is 1, 2, 3, 4, 5.

After all iterations, the sorted array is 1, 2, 3, 4, 5.

Bubble Sort Java – Using Buffered Reader

1) Buffered Reader reads the entered number as a string using readLine() method. Convert each element in to integer using Integer.parseInt().

2) printarray() prints the array elements, sort() method will sort the array elements using bubble sort logic.

Output:

Fore More: List Of All Sorting Programs In Java Here

x

Check Also

Java Inverted Mirrored Right Triangle Star Pattern

Java program to print Inverted mirrored right triangle star pattern program. We have written below ...