sorting in java - java sorting algorithms

sorting in java - java sorting algorithms

·

6 min read

This tutorial will explain the Bubble sort in java along with major java sorting algorithms, bubble sort implementation & code examples:

A sorting algorithm can be defined as an algorithm or a procedure to put elements of a collection in a specific order. For instance, if you have a numeric collection like an ArrayList of integers, then you might want to arrange the elements of ArrayList in ascending or descending order.

Similarly, you might want to arrange strings of a string collection in alphabetical or lexicographic order.

This is where the sorting algorithms in java come into the picture.

Major sorting algorithms in java

Sorting algorithms are usually evaluated depending on the time and space complexities. Java supports various sorting algorithms that are used to sort or arrange collections or data structures.

The table below shows the major sorting algorithms supported in java along with their best and worst-case complexities.

Sorting algorithmDescriptionBest caseWorst caseAverage case
Bubble sortCompares the current element to adjacent elements repeatedly. At the end of each iteration, the heaviest element gets bubbled up at its proper place.O(n)(n^2)O(n^2)
Insertion sortInserts each element of the collection in its proper place.O(n)O(n^2)O(n^2)
Merge sortit follows the divide-and-conquer approach. Divides the collection into simpler sub-collections, sorts them and then merges everythingO(N log N)O(N log N)O(N log N)
Quick sortMost efficient and optimized sorting technique. Uses divide-and-conquer to sort the collection.O(N log N)O(n^2)O(N log N)
Selection sortFinds the smallest element in the collection and put it in its proper place at the end of every iterationO(n^2)O(n^2)O(n^2)
Radix sortLinear sorting algorithmO(nk)O(nk)O(nk)
Heap sortElements are sorted bu building min heap or max heapO(N log N)O(N log N)O(N log N)

Apart from the sorting techniques given in the above table, Java also supports the following sorting techniques:

  • Bucket sort

  • Counting sort

  • Shell sort

  • Comb sort

But these techniques are used sparingly in practical applications, thus these techniques will not be part of this

Let's discuss the bubble sort technique in Java.

Bubble sort in java

Bubble sorting is the simplest of all sorting techniques in java. This technique sorts the collection by repeatedly comparing two adjacent elements and swapping them if they are not in the desired order. Thus, at the end of the iteration, the heaviest element gets bubbled up to claim its rightful position.

If there are n elements in list A given by A[0],A[1],A[2]......,A[n-1] then A[0] is compared to A[1], A[1] is compared to A[2] and so on. After comparing if the first element is greater than the second, then the two elements are swapped if they are not in order.

Bubble sort algorithm

The general algorithm for the bubble sort technique is given below:

  1. For i = 0 to N-1 repeat step 2

  2. For j=i+1 to N-i repeat

  3. if A[j]>A[I] swap A[j] and A[I]

  4. [End of inner for loop]

  5. [End of outer for loop]

  6. Exit

Now let's demonstrate the bubble sort technique using an illustrative example.

We take an array of size 5 and illustrate the bubble sort algorithm.

Sort an array using bubble sort

The following list is to be sorted.

[11,3,6,15,4]

pass 1:

[11,3,6,15,4]->[3,11,6,15,4]->[3,6,11,15,4]->[3,6,11,15,4]->[3,6,11,4,15]

the largest element bubbled up

pass 2:

[3,6,11,4,15]->[3,6,11,4,15]->[3,6,11,4,15]->[3,6,4,11,15]->[3,5,4,11,15]

The second largest element bubbled up

pass 3:

[3,6,4,11,15]->[3,6,4,11,15]->[3,4,6,11,15]->[3,4,6,11,15]

The third element bubbled up, list sorted

As you can see above, the array is entirely sorted.

The above illustration can be summarized in tabular form as shown below:

passunsorted listcomparisonsorted list
111,3,6,15,411,33,11,6,15,4
3,11,6,15,411,63,6,11,15,4
3,6,11,15,411,153,6,11,15,4
3,6,11,15,415,43,6,11,4,15
23,6,11,4,153,63,6,11,4,15
3,6,11,4,156,113,6,11,4,15
3,6,11,4,1511,43,64,11,15
3,64,11,1511,153,6,4,11,15
33,6,4,11,153,63,6,4,11,15
3,6,4,11,156,43,4,6,11,15
3,4,6,11,15sorted

As shown in the above example, the largest element bubbles up to its proper position with every iteration/pass. In general, when we reach N-1 (where N is the total number of elements in the list) passes; we will have the entire list sorted.

Bubble sort code example

The below program shows the java implementation of the bubble sort algorithm. Here, we maintain an array of numbers and use two for loops to traverse adjacent elements of the array. if two adjacent elements are not in order, then the are swapped .

import java.util.*;
class Main{
    //Driver method to test above
    public static void main(String[] args){
        //declare an array of integers 
        int[] arr = {23,43,13,65,11,62,76,83,9,7,84,34,96,80};
        //print original array
        System.out.println("Original array: "+Arrays.toString(arr));
        int n = arr.length;
        //iterate over the array comparing adjacent elements
        for(int i=0;i<n-1;i++){
            for(int j=0;j<n-i-1;j++){
                //if elements not in order, swap them
                if(arr[j]>arr[j+1]){
                    int temp = arr[j];
                    arr[j]=arr[j+1];
                    arr[j+1]=temp;
                }
            }
        }
        //print the sorted array
        System.out.println("Sorted array: "+Arrays.toString(arr));
    }
}

Output:

Original array: [23,43,13,65,11,62,76,83,9,71,84,34,96,80]

Sorted array:[9,11,13,23,34,43,62,65,71,76,80,83,84,96]

You might be having some questions here are some of the most common questions

Q1->What are the sorting algorithms in Java?

Answer: The sorting algorithm can be defined as an algorithm or procedure using which the elements in a collection can be ordered or arranged in a desired fashion.

Given below are some of the sorting algorithms supported in java:

  • Bubble sort

  • Insertion sort

  • selection sort

  • Merge sort

  • Quick sort

  • Radix sort

  • Heap sort

Q2-> What is the best sorting algorithm in java?

Answer: Merge sort is supposed to be the fastest sorting algorithm in java. In fact, java 7 has internally used merge sort to implement the Collections.sort() method. Quick sort is also another best sorting algorithm.

Q3-> What is bubble sort in java?

Answer: Bubble sort is the simplest algorithm in java. Bubble sort always compares two adjacent elements in the list and swaps them if they are not in the desired order. Thus, at the end of every iteration or pass, the heaviest element is bubbled up to its proper place.

Q4-> Why is bubble sort N^2?

Answer: For implementing bubble sort, use two for loops.

The total work done is measured by:

amount of work done by the inner loop *total number of times the outer loops run.

For a list of n elements, the inner loop works for O(n) for each iteration. The outer loop runs for O(n)iteration. Hence the total work done is O(n)*O(n) = O(n^2)

Q5-> What are the advantages of bubble sort?

Answer: advantages of bubble sort are as follows:

  1. Easy to code and understand.

  2. Few lines of code are required to implement the algorithm.

  3. The sorting is done in place i.e. additional memory is not required and thus no memory overhead.

  4. The sorted data is immediately available for processing.

Conclusion

So far, we discussed the bubble sort sorting algorithm in java. We also explored the algorithm and detailed illustration of sorting an array using the bubble sort technique. Then we implemented the java program to the bubble sort.