Une introduction à l'algorithme de tri à bulles

Une introduction à l'algorithme de tri à bulles

Le tri est l'une des opérations les plus élémentaires que vous puissiez appliquer aux données. Vous pouvez trier des éléments dans différents langages de programmation à l'aide de divers algorithmes de tri tels que le tri rapide, le tri à bulles, le tri par fusion, le tri par insertion, etc. Le tri à bulles est l'algorithme le plus simple parmi tous ceux-ci.





Dans cet article, vous découvrirez le fonctionnement de l'algorithme Bubble Sort, le pseudocode de l'algorithme Bubble Sort, sa complexité temporelle et spatiale et son implémentation dans divers langages de programmation tels que C++, Python, C et JavaScript.





Comment fonctionne l'algorithme de tri à bulles ?

Bubble Sort est l'algorithme de tri le plus simple qui parcourt la liste à plusieurs reprises, compare les éléments adjacents et les échange s'ils sont dans le mauvais ordre. Ce concept peut être expliqué plus efficacement à l'aide d'un exemple. Considérons un tableau non trié avec les éléments suivants : {16, 12, 15, 13, 19}.





Exemple:

Ici, les éléments adjacents sont comparés et s'ils ne sont pas dans l'ordre croissant, ils sont échangés.



Pseudocode de l'algorithme de tri à bulles

En pseudocode , l'algorithme Bubble Sort peut être exprimé comme :

bubbleSort(Arr[], size)
// loop to access each array element
for i=0 to size-1 do:
// loop to compare array elements
for j=0 to size-i-1 do:
// compare the adjacent elements
if Arr[j] > Arr[j+1] then
// swap them
swap(Arr[j], Arr[j+1])
end if
end for
end for
end

L'algorithme ci-dessus traite toutes les comparaisons même si le tableau est déjà trié. Il peut être optimisé davantage en arrêtant l'algorithme si la boucle interne n'a provoqué aucun échange. Cela réduira le temps d'exécution de l'algorithme.





Ainsi, le pseudocode de l'algorithme de Bubble Sort optimisé peut être exprimé sous la forme :

bubbleSort(Arr[], size)
// loop to access each array element
for i=0 to size-1 do:
// check if swapping occurs
swapped = false
// loop to compare array elements
for j=0 to size-i-1 do:
// compare the adjacent elements
if Arr[j] > Arr[j+1] then
// swap them
swap(Arr[j], Arr[j+1])
swapped = true
end if
end for
// if no elements were swapped that means the array is sorted now, then break the loop.
if(not swapped) then
break
end if
end for
end

Complexité temporelle et espace auxiliaire de l'algorithme de tri à bulles

La complexité temporelle dans le pire des cas de l'algorithme de tri à bulles est O(n^2). Cela se produit lorsque le tableau est dans l'ordre décroissant et que vous souhaitez le trier dans l'ordre croissant ou vice-versa.





bouton gauche de la souris ne fonctionne pas windows 7

La complexité temporelle dans le meilleur des cas de l'algorithme de tri à bulles est O(n). Cela se produit lorsque le tableau est déjà trié.

comment vérifier si l'iphone a un virus

En rapport: Qu'est-ce que la notation Big-O ?

La complexité temporelle moyenne de l'algorithme de tri à bulles est O(n^2). Cela se produit lorsque les éléments du tableau sont dans un ordre brouillé.

L'espace auxiliaire requis pour l'algorithme de tri à bulles est O(1).

Implémentation en C++ de l'algorithme de tri à bulles

Vous trouverez ci-dessous l'implémentation C++ de l'algorithme Bubble Sort :

// C++ implementation of the
// optimised Bubble Sort algorithm
#include
using namespace std;
// Function to perform Bubble Sort
void bubbleSort(int arr[], int size) {
// Loop to access each element of the array
for (int i=0; i<(size-1); i++) {
// Variable to check if swapping occurs
bool swapped = false;
// loop to compare two adjacent elements of the array
for (int j = 0; j <(size-i-1); j++) {
// Comparing two adjacent array elements
if (arr[j] > arr[j + 1]) {
// Swap both elements if they're
// not in correct order
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
swapped = true;
}
}
// If no elements were swapped that means the array is sorted now,
// then break the loop.
if (swapped == false) {
break;
}
}
}
// Prints the elements of the array
void printArray(int arr[], int size) {
for (int i = 0; i cout << arr[i] << ' ';
}
cout << endl;
}
int main() {
int arr[] = {16, 12, 15, 13, 19};
// Finding the length of the array
int size = sizeof(arr) / sizeof(arr[0]);
// Printing the given unsorted array
cout << 'Unsorted Array: ' << endl;
printArray(arr, size);
// Calling bubbleSort() function
bubbleSort(arr, size);
// Printing the sorted array
cout << 'Sorted Array in Ascending Order:' << endl;
printArray(arr, size);
return 0;
}

Sortir:

Unsorted Array:
16 12 15 13 19
Sorted Array in Ascending Order:
12 13 15 16 19

Implémentation Python de l'algorithme de tri à bulles

Vous trouverez ci-dessous l'implémentation Python de l'algorithme Bubble Sort :

# Python implementation of the
# optimised Bubble Sort algorithm

# Function to perform Bubble Sort
def bubbleSort(arr, size):
# Loop to access each element of the list
for i in range (size-1):
# Variable to check if swapping occurs
swapped = False
# loop to compare two adjacent elements of the list
for j in range(size-i-1):
# Comparing two adjacent list elements
if arr[j] > arr[j+1]:
temp = arr[j]
arr[j] = arr[j+1]
arr[j+1] = temp
swapped = True
# If no elements were swapped that means the list is sorted now,
# then break the loop.
if swapped == False:
break
# Prints the elements of the list
def printArray(arr):
for element in arr:
print(element, end=' ')
print('')

arr = [16, 12, 15, 13, 19]
# Finding the length of the list
size = len(arr)
# Printing the given unsorted list
print('Unsorted List:')
printArray(arr)
# Calling bubbleSort() function
bubbleSort(arr, size)
# Printing the sorted list
print('Sorted List in Ascending Order:')
printArray(arr)

Sortir:

Unsorted List:
16 12 15 13 19
Sorted List in Ascending Order:
12 13 15 16 19

En rapport: Comment utiliser les boucles For en Python

C Implémentation de l'algorithme de tri à bulles

Vous trouverez ci-dessous l'implémentation en C de l'algorithme Bubble Sort :

// C implementation of the
// optimised Bubble Sort algorithm
#include
#include
// Function to perform Bubble Sort
void bubbleSort(int arr[], int size) {
// Loop to access each element of the array
for (int i=0; i<(size-1); i++) {
// Variable to check if swapping occurs
bool swapped = false;
// loop to compare two adjacent elements of the array
for (int j = 0; j <(size-i-1); j++) {
// Comparing two adjacent array elements
if (arr[j] > arr[j + 1]) {
// Swap both elements if they're
// not in correct order
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
swapped = true;
}
}
// If no elements were swapped that means the array is sorted now,
// then break the loop.
if (swapped == false) {
break;
}
}
}
// Prints the elements of the array
void printArray(int arr[], int size) {
for (int i = 0; i printf('%d ', arr[i]);
}
printf(' ⁠n ');
}
int main() {
int arr[] = {16, 12, 15, 13, 19};
// Finding the length of the array
int size = sizeof(arr) / sizeof(arr[0]);
// Printing the given unsorted array
printf('Unsorted Array: ⁠n');
printArray(arr, size);
// Calling bubbleSort() function
bubbleSort(arr, size);
// Printing the sorted array
printf('Sorted Array in Ascending Order: ⁠n');
printArray(arr, size);
return 0;
}

Sortir:

Unsorted Array:
16 12 15 13 19
Sorted Array in Ascending Order:
12 13 15 16 19

Implémentation JavaScript de l'algorithme de tri à bulles

Vous trouverez ci-dessous l'implémentation JavaScript de l'algorithme Bubble Sort :

// JavaScript implementation of the
// optimised Bubble Sort algorithm
// Function to perform Bubble Sort
function bubbleSort(arr, size) {
// Loop to access each element of the array
for(let i=0; i // Variable to check if swapping occurs
var swapped = false;
// loop to compare two adjacent elements of the array
for(let j=0; j // Comparing two adjacent array elements
if(arr[j] > arr[j+1]) {
// Swap both elements if they're
// not in correct order
let temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
swapped = true;
}
// If no elements were swapped that means the array is sorted now,
// then break the loop.
if (swapped == false) {
break;
}
}
}
}
// Prints the elements of the array
function printArray(arr, size) {
for (let i=0; i document.write(arr[i] + ' ');
}
document.write('
')
}

var arr = [16, 12, 15, 13, 19];
// Finding the length of the array
var size = arr.length;
// Printing the given unsorted array
document.write('Unsorted Array:
');
printArray(arr, size);
// Calling bubbleSort() function
bubbleSort(arr, size);
// Printing the sorted array
document.write('Sorted Array in Ascending Order:
');
printArray(arr, size);

Sortir:

Unsorted Array:
16 12 15 13 19
Sorted Array in Ascending Order:
12 15 13 16 19

Vous comprenez maintenant le fonctionnement de l'algorithme de tri à bulles

Bubble Sort est l'algorithme de tri le plus simple et est principalement utilisé pour comprendre les fondements du tri. Le tri à bulles peut également être implémenté de manière récursive, mais cela n'offre aucun avantage supplémentaire.

En utilisant Python, vous pouvez facilement implémenter l'algorithme Bubble Sort. Si vous n'êtes pas familier avec Python et que vous souhaitez démarrer votre voyage, commencer avec un script 'Hello World' est un excellent choix.

Partager Partager Tweeter E-mail Comment démarrer avec Python à l'aide d'un script 'Hello World'

Python est l'un des langages de programmation les plus utilisés aujourd'hui. Suivez ce tutoriel pour commencer avec votre tout premier script Python.

Lire la suite
Rubriques connexes
  • La programmation
  • Java
  • Python
  • Tutoriels de codage
A propos de l'auteur Yuvraj Chandra(60 articles publiés)

Yuvraj est un étudiant de premier cycle en informatique à l'Université de Delhi, en Inde. Il est passionné par le développement Web Full Stack. Quand il n'écrit pas, il explore la profondeur de différentes technologies.

comment connecter une manette xbox a un pc
Plus de Yuvraj Chandra

Abonnez-vous à notre newsletter

Rejoignez notre newsletter pour des conseils techniques, des critiques, des ebooks gratuits et des offres exclusives !

Cliquez ici pour vous abonner