Una introducció a l'algorisme de classificació de bombolles

Una introducció a l'algorisme de classificació de bombolles

L’ordenació és una de les operacions més bàsiques que podeu aplicar a les dades. Podeu ordenar elements en diferents llenguatges de programació mitjançant diversos algoritmes d’ordenació com ara Classificació ràpida, Classificació de bombolles, Classificació de combinació, Classificació per inserció, etc.





En aquest article, coneixereu el funcionament de l'algorisme Bubble Sort, el pseudocodi de l'algorisme Bubble Sort, la seva complexitat temporal i espacial i la seva implementació en diversos llenguatges de programació com C ++, Python, C i JavaScript.





Com funciona l'algorisme de classificació de bombolles?

Bubble Sort és l’algorisme d’ordenació més senzill que recorre la llista repetidament, compara els elements adjacents i els canvia si estan en un ordre incorrecte. Aquest concepte es pot explicar de manera més eficient amb l'ajut d'un exemple. Penseu en una matriu sense classificar amb els elements següents: {16, 12, 15, 13, 19}.





Exemple:

Aquí es comparen els elements adjacents i, si no estan en ordre ascendent, es canvien.



Pseudocodi de l'algorisme de classificació de bombolles

En pseudocodi, l'algorisme de classificació de bombolles es pot expressar com:

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'algoritme anterior processa totes les comparacions fins i tot si la matriu ja està ordenada. Es pot optimitzar encara més aturant l'algoritme si el bucle intern no va provocar cap intercanvi. Això reduirà el temps d'execució de l'algorisme.





Per tant, el pseudocodi de l'algorisme de Bubble Sort optimitzat es pot expressar com:

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

Complexitat temporal i espai auxiliar de l'algorisme de classificació de bombolles

La pitjor complexitat temporal de l'algorisme de classificació de bombolles és O (n ^ 2). Es produeix quan la matriu està en ordre descendent i es vol ordenar en ordre ascendent o viceversa.





el clic esquerre del ratolí no funciona de vegades Windows 10

La complexitat temporal dels millors casos de l'algorisme de classificació de bombolles és O (n). Es produeix quan la matriu ja està ordenada.

com capturar una història de Snapchat sense que ho sàpiguen

Relacionat: Què és la notació Big-O?

La complexitat del temps mitjà-cas de l'algorisme de classificació de bombolles és O (n ^ 2). Es produeix quan els elements de la matriu estan en ordre confús.

L'espai auxiliar necessari per a l'algorisme de classificació de bombolles és O (1).

Implementació de C ++ de l'algorisme de classificació de bombolles

A continuació es mostra la implementació de C ++ de l’algorisme 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;
}

Sortida:

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

Implementació de Python de l'algorisme de classificació de bombolles

A continuació es mostra la implementació de Python de l’algorisme 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)

Sortida:

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

Relacionat: Com s'utilitza per a bucles a Python

C Implementació de l'algorisme de classificació de bombolles

A continuació es mostra la implementació en C de l'algorisme 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;
}

Sortida:

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

Implementació de JavaScript de l'algorisme de classificació de bombolles

A continuació es mostra la implementació de JavaScript de l’algorisme 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);

Sortida:

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

Ara enteneu el funcionament de l'algorisme de classificació de bombolles

Bubble Sort és l’algorisme d’ordenació més senzill i s’utilitza principalment per entendre els fonaments de l’ordenació. Bubble Sort també es pot implementar recursivament, però no proporciona avantatges addicionals per fer-ho.

Mitjançant Python, podeu implementar l’algoritme Bubble Sort amb facilitat. Si no esteu familiaritzat amb Python i voleu iniciar el vostre viatge, començar amb un guió 'Hello World' és una bona opció.

Compartir Compartir Tweet Correu electrònic Com començar amb Python mitjançant un script 'Hello World'

Python és un dels llenguatges de programació més populars que s’utilitzen actualment. Seguiu aquest tutorial per començar amb el vostre primer script Python.

Llegiu a continuació
Temes relacionats
  • Programació
  • Java
  • Python
  • Tutorials de codificació
Sobre l'autor Yuvraj Chandra(60 articles publicats)

Yuvraj és estudiant universitari en ciències de la computació a la Universitat de Delhi, Índia. És un apassionat del desenvolupament web Full Stack. Quan no escriu, explora la profunditat de les diferents tecnologies.

com ss un instantani sense que ho sàpiguen
Més de Yuvraj Chandra

Subscriu-te al nostre butlletí

Uniu-vos al nostre butlletí per obtenir consells tècnics, ressenyes, llibres electrònics gratuïts i ofertes exclusives.

Feu clic aquí per subscriure-us