Not only is it not considered the fastest method, moreover, it closes the list of the slowest ordering methods. However, it also has its advantages. So, bubble sorting is the most logical and natural solution to the problem if you need to arrange elements in a certain order. An ordinary person, for example, will use it manually - simply by intuition.

Where did such an unusual name come from?

The name of the method was invented using an analogy with air bubbles in water. This is a metaphor. Just as small air bubbles rise to the top - after all, their density is greater than that of any liquid (in this case, water), so each element of the array, the smaller it is in value, the more it gradually makes its way to the beginning of the list of numbers.

Description of the algorithm

Bubble sort works like this:

  • first pass: elements of the array of numbers are taken two at a time and also compared in pairs. If in some pair of elements the first value is greater than the second, the program swaps them;
  • therefore ends up at the end of the array. While all other elements remain as they were, in a chaotic order and require further sorting;
  • that is why a second pass is necessary: ​​it is performed by analogy with the previous one (already described) and has the number of comparisons - minus one;
  • Passage number three has one fewer comparisons than the second, and two less than the first. And so on;
  • Let's summarize that each pass has (total values ​​in the array, a specific number) minus (pass number) comparisons.

Even more briefly, the algorithm of the future program can be written as follows:

  • the array of numbers is checked until any two numbers are found, and the second of them must be greater than the first;
  • The program swaps array elements that are incorrectly positioned in relation to each other.

Pseudocode based on the described algorithm

The simplest implementation goes like this:

Procedure Sortirovka_Puzirkom;

Start

loop for j from initial_index to konechii_index;

loop for i from initial_index to konechii_index-1;

If massiv[i]>massiv

(swap the values);

End

Of course, here simplicity only aggravates the situation: the simpler the algorithm, the more all the shortcomings appear in it. The time consumption is too great even for a small array (relativity comes into play here: for the average person, the amount of time may seem small, but in the business of a programmer, every second or even millisecond counts).

A better implementation was needed. For example, taking into account the swapping of values ​​in an array:

Procedure Sortirovka_Puzirkom;

Start

sortirovka = true;

cycle so far sortirovka = true;

sortirovka = false;

loop for i from initial_index to konechii_index-1;

If massiv[i]>massiv(the first element is greater than the second), then:

(swap elements);

sortirovka = true; (indicated that the exchange was made).

End.

Disadvantages of the method

The main disadvantage is the duration of the process. How long does it take to make a bubble?

The execution time is calculated from the square of the number of numbers in the array - the final result is proportional to it.

In the worst case scenario, the array will be traversed the same number of times as there are elements in it minus one value. This happens because eventually there is only one element left with nothing to compare with, and the last pass through the array becomes a useless action.

In addition, the simple exchange sorting method, as it is also called, is effective only for small arrays. It will not be possible to process large amounts of data with its help: the result will be either errors or program failure.

Advantages

Bubble sort is quite simple to understand. In the curricula of technical universities, when studying the ordering of array elements, it is covered first. The method is easily implemented in both the Delphi programming language (D) and C/C++ (C/C plus plus), an incredibly simple algorithm for arranging values ​​in the correct order, and Bubble Sort is ideal for beginners.

Due to its shortcomings, the algorithm is not used for extracurricular purposes.

Visual sorting principle

Initial view of the array 8 22 4 74 44 37 1 7

Step 1 8 22 4 74 44 37 1 7

8 22 4 74 44 1 37 7

8 22 4 74 1 44 37 7

8 22 4 1 74 44 37 7

8 22 1 4 74 44 37 7

8 1 22 4 74 44 37 7

1 8 22 4 74 44 37 7

Step 2 1 8 22 4 74 44 7 37

1 8 22 4 74 7 44 37

1 8 22 4 7 74 44 37

1 8 22 4 7 74 44 37

1 8 4 22 7 74 44 37

1 4 8 22 7 74 44 37

Step 3 1 4 8 22 7 74 37 44

1 4 8 22 7 37 74 44

1 4 8 22 7 37 74 44

1 4 8 7 22 37 74 44

1 4 7 8 22 37 74 44

Step 4 1 4 7 8 22 37 44 74

1 4 7 8 22 37 44 74

1 4 7 8 22 37 44 74

1 4 7 8 22 37 44 74

Step 5 1 4 7 8 22 37 44 74

1 4 7 8 22 37 44 74

1 4 7 8 22 37 44 74

Step 6 1 4 7 8 22 37 44 74

1 4 7 8 22 37 44 74

Step 7 1 4 7 8 22 37 44 74

Example of bubble sort in Pascal

Example:

const kol_mas=10;

var array:array of integer;

a, b, k: integer;

writeln("input", kol_mas, "elements of array");

for a:=1 to kol_mas do readln(array[a]);

for a:=1 to kol_mas-1 do begin

for b:=a+1 to kol_mas do begin

if massiv[a]>massiv[b] then begin

k:=array[a]; massiv[a]:=massiv[b]; array[b]:=k;

end;

writeln("after sort");

for a:=1 to kol_mas do writeln(massiv[a]);

Example of bubble sort in C language

#include

#include

int main(int argc, char* argv)

int massiv = (36, 697, 73, 82, 68, 12, 183, 88),i, ff;

for (; ;)(

ff = 0;

for (i = 7; i>0; i--)(

if (array[i]< massiv) {

swap(array[i],massiv);

if (ff == 0) break;

getch(); // screen delay


Let's arrange the array from top to bottom, from the zero element to the last.

The idea of ​​the method: the sorting step consists of going from bottom to top through the array. Along the way, pairs of neighboring elements are viewed. If the elements of a certain pair are in the wrong order, then we swap them.

After zero passes through the array, the lightest element appears at the top - hence the analogy with a bubble. The next pass is made to the second element from the top, thus lifting the second largest element to the correct position...

We make passes along the ever-decreasing lower part of the array until only one element remains in it. This is where the sorting ends, since the sequence is ordered in ascending order.

Template void bubbleSort(T a, long size) ( long i, j; T x; for(i=0; i< size; i++) { // i - pass number for(j = size-1; j > i; j--) ( // inner loop loop if (a > a[j]) ( x=a; a=a[j]; a[j]=x; ) ) ) )

The average number of comparisons and exchanges has a quadratic growth order: Theta(n 2), from which we can conclude that the bubble algorithm is very slow and ineffective.
However, it has a huge advantage: it is simple and can be improved in every way. What are we going to do now?

First, let's consider a situation where not a single exchange occurred on any of the passes. What does it mean?

This means that all pairs are in the correct order, so the array is already sorted. And it makes no sense to continue the process (especially if the array was sorted from the very beginning!).

So, the first improvement of the algorithm is to remember whether any exchange was made on a given pass. If not, the algorithm terminates.

The improvement process can be continued if you remember not only the fact of the exchange itself, but also the index of the last exchange k. Indeed: all pairs of neighboring elements with indices less than k are already located in the required order. Further passes can end at index k, instead of moving to the pre-set upper bound i.

A qualitatively different improvement of the algorithm can be obtained from the following observation. Although a light bubble at the bottom will rise to the top in one pass, heavy bubbles will sink at a minimal rate: one step per iteration. So the array 2 3 4 5 6 1 will be sorted in 1 pass, but sorting the sequence 6 1 2 3 4 5 will require 5 passes.

To avoid this effect, you can change the direction of successive passes. The resulting algorithm is sometimes called " shaker sorting".

Template void shakerSort(T a, long size) ( long j, k = size-1; long lb=1, ub = size-1; // boundaries of the unsorted part of the array Tx; do ( // pass from bottom to top for(j=ub; j>0; j--) ( if (a > a[j]) ( x=a; a=a[j]; a[j]=x; k=j; ) ) lb = k+1; // pass from top to bottom for (j=1; j<=ub; j++) { if (a >a[j]) ( x=a; a=a[j]; a[j]=x; k=j; ) ) ub = k-1; ) while (lb< ub); }

How much did the described changes affect the effectiveness of the method? The average number of comparisons, although decreased, remains O(n 2), while the number of exchanges has not changed at all. The average (aka worst) number of operations remains quadratic.

Additional memory is obviously not required. The behavior of the improved (but not the initial) method is quite natural; an almost sorted array will be sorted much faster than a random one. Bubble sorting is stable, but shaker sorting loses this quality.

In practice, the bubble method, even with improvements, works, alas, too slowly. And therefore it is almost never used.

It has been estimated that up to a quarter of the time of centralized computers is spent sorting data. This is because it is much easier to find a value in an array that has been pre-sorted. Otherwise, the search is a bit like looking for a needle in a haystack.

There are programmers who spend all their working time studying and implementing sorting algorithms. This is because the vast majority of business software involves database management. People search databases for information all the time. This means that search algorithms are in high demand.

But there is one "but". Search algorithms work much faster with databases that are already sorted. In this case, only a linear search is required.

While the computers are without users at some points in time, the sorting algorithms continue to operate on the databases. Searchers come again, and the database is already sorted based on one or another search purpose.

This article provides implementation examples standard algorithms sorting.

Selection sort

In order to sort an array in ascending order, you must find the element with the largest value at each iteration. With it you need to swap the last element. The next element with the highest value is placed in second to last place. This should happen until the elements in the first places in the array are in the proper order.

C++ code

void SortAlgo::selectionSort(int data, int lenD) ( int j = 0; int tmp = 0; for (int i=0; i data[k])( j = k; ) ) tmp = data[i]; data[i] = data[j]; data[j] = tmp; ) )

Bubble sort

Bubble sort compares adjacent elements and swaps places if the next element is smaller than the previous one. Multiple passes through the data are required. During the first pass, the first two elements in the array are compared. If they are not in order, they are swapped and then the elements in the next pair are compared. Under the same condition, they also change places. Thus, sorting occurs in each cycle until the end of the array is reached.

C++ code

void SortAlgo::bubbleSort(int data, int lenD) ( int tmp = 0; for (int i = 0;i =(i+1);j--)( if (data[j]

Insertion sort

Insertion sort splits the array into two regions: ordered and unordered. Initially, the entire array is an unordered region. In the first pass, the first element from the unordered region is removed and placed in the correct position in the ordered region.

On each pass, the size of the ordered region increases by 1, and the size of the disordered region decreases by 1.

The main loop runs from 1 to N-1. At the jth iteration, element [i] is inserted into the correct position in the ordered region. This is done by shifting all elements of the ordered region that are greater than [i] one position to the right. [i] is inserted into the space between those elements that are less than [i] and those that are greater than [i].

C++ code

void SortAlgo::insertionSort(int data, int lenD) ( int key = 0; int i = 0; for (int j = 1;j =0 && data[i]>key)( data = data[i]; i = i-1; data=key; ) ) )

Merge sort

C++ code

void SortAlgo::mergeSort(int data, int lenD) ( if (lenD>1)( int middle = lenD/2; int rem = lenD-middle; int * L = new int; int * R = new int; for ( int i=0;i

Quick sort

Quicksort uses a divide and conquer algorithm. It begins by splitting the original array into two areas. These parts are to the left and right of the marked element, called the support. At the end of the process, one part will contain elements smaller than the reference, and the other part will contain elements larger than the reference.

C++ code

void SortAlgo::quickSort(int * data, int const len) ( int const lenD = len; int pivot = 0; int ind = lenD/2; int i,j = 0,k = 0; if (lenD>1) ( int * L = new int ; int * R = new int ; pivot = data; for (i=0;i 

Bubble method

Sorting by simple exchanges, bubble sort (English bubble sort) - simple sorting algorithm. This algorithm is the simplest to understand and implement, but it is effective only for small arrays. Algorithm complexity: O( n²).

The algorithm is considered educational and is practically not used outside educational literature; instead, it is used in practice insertion sort.

Algorithm

An example of bubble sorting a list of random numbers.

The algorithm consists of repeated passes through the sorted array. For each pass, the elements are sequentially compared in pairs and, if the order in the pair is incorrect, the elements are exchanged. Passes through the array are repeated until the next pass turns out that the exchanges are no longer needed, which means the array is sorted. When passing through the algorithm, an element that is out of place “floats up” to the desired position like a bubble in water, hence the name of the algorithm.

Sometimes at each step the array is scanned from the beginning, then from the end. It's called shaker sorting.

Implementation examples

Python

Def swap(arr, i, j) : arr[ i] , arr[ j] = arr[ j] , arr[ i] def bubble_sort(arr) : i = len (arr) while i > 1 : for j in xrange (i - 1 ) : if arr[ j] > arr[ j + 1 ] : swap(arr, j, j + 1 ) i -= 1

VBA

Sub Sort(Mus() As Long ) Dim n As Long , i As Long , tmp As Long i = 1 Do While (i< UBound (Mus) ) If Mus(i) >Mus(i + 1 ) Then tmp = Mus(i) Mus(i) = Mus(i + 1 ) Mus(i + 1 ) = tmp If i > 1 Then i = i - 1 Else i = i + 1 End If Else i = i + 1 End If Loop End Sub

Improved bubble sort algorithm in Pascal

P:=True ; (There is a rearrangement) K:=1 ; (View number) While P Do Begin P:=false ; For i:=1 To n-k Do If X[ i] > X[ i+1 ] Then Begin A:=X[ i] ; X[ i] :=X[ i+1 ] ; X[ i+1 ] :=A; P:=true ; End ; k:=k+1 ; End ;

PHP

$size = count ($arr ) -1 ; for ($i = $size ; $i >=0 ; $i --) ( for ($j = 0 ; $j<=($i -1 ) ; $j ++) if ($arr [ $j ] >$arr [ $j +1 ] ) ( $k = $arr [ $j ] ; $arr [ $j ] = $arr [ $j +1 ] ; $arr [ $j +1 ] = $k ; ) )


Close