neroplan.blogg.se

Bubble sort
Bubble sort









The algorithm starts with the first two elements (with indices 0 and 1), 8 and 7, and checks if they are in the correct order.

bubble sort

If it isn’t we stop our running along the array.īubble sort exampleLet's sort the array of integers, the one, you may see below on a picture. We can improve an algorithm a little bit with checking out if at least one exchange at the previous step was made. We’ve got the second biggest element at the next-to-last place. We repeat the first step from the first to the next-to-last element. That’s the reason of the Bubble sort algorithm name. You may say, the biggest element “pops up”. At the first pass at the end it will appear the biggest element (if we sort in ascending order). If they are in the wrong order (the left neighbor is bigger than the right one), we swap them. How does bubble sort workLet's say, we need to sort an array of integers in ascending order, that is, from the smallest to the biggest number.įirst, we are going along the entire array and compare every 2 neighboring elements. For example we can sort Array or ArrayList of integers, Strings and so on. By the way, the elements of what? In Java, we can compare the elements of Collections. Hence, the elements must be comparable with each other.

bubble sort

For example, numbers in ascending or descending order or words alphabetically.

bubble sort

If we can compare two or more elements or objects by any of their attributes, it means that they can be sorted by this attribute. What is sortingFirst of all, you need to understand what sorting is in general and what we can sort in Java programs. Java Bubble sort algorithm is very easy to understand, however it is not an efficient one. This algorithm is usually used for learning purposes or you may get it as a task in your Java Junior Interview. Every programmer knows bubble sort (or at least heard of it while learning) not because it is the best sorting algorithm in the world, but the easiest one. If you have ever heard of sorting methods in programming, most likely it was the bubble sort algorithm.











Bubble sort