Java Sorting Algorithm: Bubble Sort



Programming, the need to order the collections of data or objects that must then be manipulated often arises. Ordering a list can be useful in cases where you have to do very quick searches. We will see later on how to maintain an ordered list is useful to carry out dichotomous searches and therefore have the results in a clearly lesser time compared to a sequeial search.

In this article we will refer to arrays composed of integer numbers. The algorithm is the same for every data type.

Algorithms' property

This is a speech that I do now and it is the same for every algorithm that we will study in the next articles.

Generally, every algorithm has properties that are useful in order to study them and above all, usefull to decide what algorithm is the best for the situation that is been considered. Let's see better.

Stability

An algorithm is called stable if it preserves the relative order of the data with identical keys within the file to be ordered. For example, if we are looking at a list of people sorted in alphabetical order, a stable algorithm will always return an ordered list in alphabetical order. If the algorithm were unstable, a list would be obtained without any trace of the previous ordering.

A possible way to force the stability of an algorithm is the one of adding a unique key for every element. This principle is similar to one rule of database design.

In-place

An algorithm is called in-place if it uses a constant number of variables to sort the array and it doesn't uses auxiliary arrays.

Adaptivity

An algorithm is called adaptive it if gains advantage from the elements that are already sorted.

Let's analyze better some implementations of a sorting algorithm: the Bubble Sort.

Bubble Sort

The Bubble Sort is a sorting algorithm that is not very efficient. It is often used for educational pourposes to introduce the concept of sorting algorithm.

Why "bubble sort"?

The algorithm's name comes from its behavior. In fact the elements of the vector behave exactly like the bubbles in a glass of champagne: the larger ones rise upwards while the smaller ones remain at the bottom, exactly as shown in the gif below.

Bubble sort gif

Flow-chart

Flow chart

Implementation

The flow-chart shows an optimized version of the algorithm, while the code shown below presents the classic version.

  public static void bubbleSort(int[] v) {  
          int n = v.length;  
          int temp = 0;  
           for(int index=0; index < n; index++){  
                   for(int j=1; j < (n-index); j++){  
                            if(v[j-1] > v[j]){  
                                   //swap elements
                                   temp = v[j-1];  
                                   v[j-1] = v[j];  
                                   v[j] = temp;  
                           }  
                   }  
           }  
}

This iterative implementation shows the exact procedure shown in the gif. In fact, printing step by step the various states of the array during the sorting process, we obtain:

[6, 5, 3, 1, 8, 7, 2, 4]
[5, 3, 1, 6, 7, 2, 4, 8]
[3, 1, 5, 6, 2, 4, 7, 8]
[1, 3, 5, 2, 4, 6, 7, 8]
[1, 3, 2, 4, 5, 6, 7, 8]
[1, 2, 3, 4, 5, 6, 7, 8]
[1, 2, 3, 4, 5, 6, 7, 8]
[1, 2, 3, 4, 5, 6, 7, 8]
[1, 2, 3, 4, 5, 6, 7, 8]

Notiamo come il numero di passaggi che si devono fare per ordinare un array relativamente piccolo come quello dell'esempio sia veramente alto. Proprio per questo il bubble sort viene utilizzato fondamentalmente a scopi didattici a causa della sua inefficcienza. Proprio grazie alla predisposizione all'uso didattico, andiamo a fornire un'implementazione ricorsiva dello stesso algoritmo, definendo con swap il metodo che scambia due posizioni di uno stesso array.

We can notice that the number of iterations needed to sort a short array like the one shown above is very high. Because of this the Bubble Sort is used basically for educational pourposes because of its inefficiency. Thanks to the predisposition to didactic uses, we are now going to provide a recursive implementation of the same algorithm, defining with swap the method that exchanges two positions of the same array.

    //recursive method to implement bubble sort on a subarray
    public static void bubbleSort(int[] v, int n)
    {
        for (int index = 0; index < n - 1; index++) {
            if (arr[index] > arr[index + 1]) {
                swap(arr, index, index + 1);
            }
        }
        if (n - 1 > 1) {
            bubbleSort(arr, n - 1);
        }
    }

The obtained result is the same, but the way it is realized changes.

Properties

Carrying on the speech about the properties done before, we can try to identify what are bubble sort's properties.

The Bubble Sort is stable, in fact it always returns an array sorted in ascending or descending order regardless of the data in the collection.

It is also in-place since it doesn't uses and addictional arrays for the sorting operations.

It is also adaptive, in fact when the elements are sorted, the algorithm doesn't perform any operation and keep them sorted. This feature saves a considerable number of iterations.

Complexity

Making a more mathematical speech, let's see something about the complexity of the algorithm. Let's make a small introduction. Complexity is indicated by the so-called Landau symbols, used to compare the progress of two functions. In fact, we tend to associate the complexity of an algorithm with a function, to then compare it to a note.

Assuming that the complexity of a single swap is O(1), the complexity of the algorithm is given from the nested for cycles.

In the worst case we have a complexity of T(n)=n(n-1)/2  —> O(N²while in the best case the array is already sorted and the number of iterations is 1.

On average, it performs around N2 / 2 comparisons and as many exchanges.

Optimizations and conclusions

A first way to optimize the algorithm is based on the fact that if in a certain iteration n no swaps are done, the array is sorted and then the algorithm can end. We use a boolean variable that check this condition. This kind of optimization is the one shown in the flow-chart above.

A second line of thought argues that if a given iteration does not move any element of position greater than a given value i, then you can easily demonstrate that no subsequent iteration will perform swaps in positions subsequent to that value i. The optimization consists in storing the index where the last exchange took place and scanning the array up to that value location. Even this technique obviously introduces a small overhead.

Ending the speech, we can say that the algorithm is very suitable for educational pourposes as I said before. It is not very suitable for sorting big arrays.

Spezzando una lancia a suo favore, è facile da capire e implementare, non richiede un grande ammontare di memoria e la cosa più importante è che, una volta finito l'ordinamento, i dati sono pronti per l'elaborazione.

But it has also some good points. In fact it is easy to understand and implement, it does not require a large amount of memory and the most important thing is that, once the sorting is finished, the data is ready for processing.

 
by Alessio Mungelli Date: 15-12-2019 java jdk jre developing tutorial sort sorting operation complexity bubble bubblesort algorithm sortingmethod hits : 3593  
 
Alessio Mungelli

Alessio Mungelli

Computer Science student at UniTo (University of Turin), Network specializtion, blogger and writer. I am a kind of expert in Java desktop developement with interests in AI and web developement. Unix lover (but not Windows hater). I am interested in Linux scripting. I am very inquisitive and I love learning new stuffs.

 
 
 

Related Posts

Strings in JavaScript: What they are and how to use them

In this tutorial we are going to explain what strings are and how they are used in JavaScript. The tutorial is intended for people who are learning to program in…

Dates in local format with Javascript

In the articles we have about dates in JavaScript we were missing one about how to create dates in local format with JavaScript. That is to say, being able to…

Formatting hours in Javascript

Continuing with the set of articles that talk about internationalisation elements, like the previous one where we talked about relative dates in JavaScript, we will see in this one how…

Request data with prompt in JavaScript

After having published several articles about how to manipulate arrays and dates, today I will publish a post that some of you will find too basic and others will find…

Relative dates in JavaScript

One of the interesting things about the internationalisation library represented in the Int object is the handling of relative dates in Javascript. This handling allows us to represent a date…

How to access webcam and grab an image using HTML5 and Javascript

We often use webcams to broadcast video in real time via our computer. This broadcast can be viewed, saved and even shared via the Internet. As a rule, we need…

The JavaScript forEach loop

We have already talked about how to handle some of loops  types in Javascript including for, for-in and for-off loops. In the case of today we are going to see how…

What are React Hooks and what problems they solve

Working with React, - and before the release of Hooks in version 16.8 -  there was always the possibility to create components in three different ways based on a number of…

Flattening arrays in JavaScript

When we are handling arrays that are arrays or have multiple dimensions it can be very useful to know how to flatten arrays in JavaScript. That is to say, to…

How to populate an array with random numbers in JavaScript

Some of you might think that what we explained in the article on how to populate an array with numbers, apart from the didactic part, would not have much applicability…

How to populate an array with numbers in JavaScript

Populate an array with numbers in JavaScript The first step is to initialise the array. So today we are going to see a simple way to do it and see how…

Top Javascript Libraries and Frameworks Part 2

What are JavaScript frameworks?   JavaScript frameworks are application frameworks that allow developers to manipulate code to meet their particular needs. Web application development is like building a house. You have the option…

We use our own and third-party cookies to improve our services, compile statistical information and analyze your browsing habits. This allows us to personalize the content we offer and to show you advertisements related to your preferences. By clicking "Accept all" you agree to the storage of cookies on your device to improve website navigation, analyse traffic and assist our marketing activities. You can also select "System Cookies Only" to accept only the cookies required for the website to function, or you can select the cookies you wish to activate by clicking on "settings".

Accept All Only sistem cookies Configuration