Bubble Sort in Java

Price: INR 8,999.00
Price: INR 15,999.00
Was: INR 16,999.00

Today we will see, How can you perform Bubble Sort in Java. Bubble sort is sorting algorithm which is used to Sort Array in Java.

 

Using Bubble sort algorithm we sort an unsorted array by starting from the first element and comparing with an adjacent element. If the first element is greater than later then we swap and by doing this we get the largest number at the end of the first iteration. So in order to sort n elements, you require n-1 iteration and almost n-1 comparison. For the recap here is the logic for bubble sort sorting algorithm :

So in order to sort n elements, you require n-1 iteration and almost n-1 comparison. Let’s look at the pseudo code for bubble sort –

 

Bubble Sort in Java

Let’s suppose we have an Array of size 10 arraay[10] –

  • Start comparing Array Elements one by one a[0] to a[1]
  • If a[0] > a[1] then swap numbers e.g. a[0]=a[1] and a[1]=a[0]
  • Compare a[1] to a[2] and repeat till you compare last pair
  • This is referred as one pass and at the end of first pass largest number is at last
  • Repeat this comparison again starting from a[0] but this time going till second last pair only

Now let’s see Java program which implements this bubble sort logic to sort unsorted integer array.

Output : 

unsorted array before sorting : [25, 82, 12, 65, 45, 69, 74, 3]
Size of Array is : 8
unsorted array after 1 pass [25, 12, 65, 45, 69, 74, 3, 82]:
unsorted array after 2 pass [12, 25, 45, 65, 69, 3, 74, 82]:
unsorted array after 3 pass [12, 25, 45, 65, 3, 69, 74, 82]:
unsorted array after 4 pass [12, 25, 45, 3, 65, 69, 74, 82]:
unsorted array after 5 pass [12, 25, 3, 45, 65, 69, 74, 82]:
unsorted array after 6 pass [12, 3, 25, 45, 65, 69, 74, 82]:
unsorted array after 7 pass [3, 12, 25, 45, 65, 69, 74, 82]:
Sorted Array after Bubble Sort : [3, 12, 25, 45, 65, 69, 74, 82]

 

That’s all on How to sort integer array using Bubble sort in Java. We have seen a complete Java program for bubble sort and also printed output after each pass or iteration, if you look at carefully you will find that after each pass largest number gets sorted and the number of comparisons decreased.

0 Comment

Leave a Reply