# 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.

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.

### 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 : 6304

#### 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

#### How to use the endsWith method in JavaScript

In this short tutorial, we are going to see what the endsWith method, introduced in JavaScript ES6, is and how it is used with strings in JavaScript. The endsWith method is…

Symbols are a new primitive value introduced by ES6. Their purpose is to provide us unique identifiers. In this article, we tell you how they work, in which way they…

#### Callbacks in JavaScript

Callback functions are the same old JavaScript functions. They have no special syntax, as they are simply functions that are passed as an argument to another function. The function that receives…

#### How to create PDF with JavaScript and jsPDF

Creating dynamic PDF files directly in the browser is possible thanks to the jsPDF JavaScript library. In the last part of this article we have prepared a practical tutorial where I…

When I started browsing different and original websites to learn from them, one of the first things that caught my attention was that some of them had their own cursors,…

#### Node.js and npm: introductory tutorial

In this tutorial we will see how to install and use both Node.js and the npm package manager. In addition, we will also create a small sample application. If you…

#### How to connect to MySQL with Node.js

Let's see how you can connect to a MySQL database using Node.js, the popular JavaScript runtime environment. Before we start, it is important to note that you must have Node.js installed…

#### JavaScript Programming Styles: Best Practices

When programming with JavaScript there are certain conventions that you should apply, especially when working in a team environment. In fact, it is common to have meetings to discuss standards…

#### Difference between arrow and normal functions in JavaScript

In this tutorial we are going to see how arrow functions differ from normal JavaScript functions. We will also see when you should use one and when you should use…

#### JavaScript Arrow functions: What they are and how to use them

In this article we are going to see what they are and how to use JavaScript Arrow Functions, a new feature introduced with the ES6 standard (ECMAScript 6). What are Arrow…

#### How to insert an element into an array with JavaScript

In this brief tutorial you will learn how to insert one or more elements into an array with JavaScript. For this we will use the splice function. The splice function will not…

#### What is the difference between primitives types and objects in JavaScript?

In this short tutorial we are going to look at the differences between primitive types and objects in JavaScript. To start with, we're going to look at what primitive types…