O introducere în algoritmul de sortare cu bule

O introducere în algoritmul de sortare cu bule

Sortarea este una dintre cele mai de bază operații pe care le puteți aplica datelor. Puteți sorta elemente în diferite limbaje de programare folosind diverși algoritmi de sortare, cum ar fi Sortare rapidă, Sortare cu bule, Sortare prin îmbinare, Sortare prin inserție, etc. Sortarea cu bule este cel mai simplu algoritm dintre toate acestea.





În acest articol, veți afla despre funcționarea algoritmului Bubble Sort, pseudocodul algoritmului Bubble Sort, complexitatea sa de timp și spațiu și implementarea sa în diferite limbaje de programare precum C ++, Python, C și JavaScript.





Cum funcționează algoritmul de sortare cu bule?

Bubble Sort este cel mai simplu algoritm de sortare care parcurge în mod repetat lista, compară elementele adiacente și le schimbă dacă sunt în ordinea greșită. Acest concept poate fi explicat mai eficient cu ajutorul unui exemplu. Luați în considerare o matrice nesortată cu următoarele elemente: {16, 12, 15, 13, 19}.





Exemplu:

Aici sunt comparate elementele adiacente și dacă nu sunt în ordine crescătoare, sunt schimbate.



Pseudocodul algoritmului de sortare cu bule

În pseudocod, algoritmul Bubble Sort poate fi exprimat ca:

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

Algoritmul de mai sus procesează toate comparațiile, chiar dacă matricea este deja sortată. Poate fi optimizat în continuare prin oprirea algoritmului dacă bucla interioară nu a provocat niciun schimb. Acest lucru va reduce timpul de execuție al algoritmului.





Astfel, pseudocodul algoritmului optimizat de sortare a bulelor poate fi exprimat ca:

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

Complexitatea timpului și spațiul auxiliar al algoritmului de sortare a bulelor

Cea mai proastă situație de timp a algoritmului de sortare a bulelor este O (n ^ 2). Apare atunci când matricea este în ordine descrescătoare și doriți să o sortați în ordine crescătoare sau invers.





cum să descărcați filme pe computer

Complexitatea în cel mai bun caz al algoritmului de sortare a bulelor este O (n). Apare atunci când matricea este deja sortată.

cum să adormi computerul

Legate de: Ce este notația Big-O?

Complexitatea timpului mediu al cazului algoritmului de sortare a bulelor este O (n ^ 2). Apare atunci când elementele matricei sunt în ordine confuză.

Spațiul auxiliar necesar algoritmului Sortare cu bule este O (1).

C ++ Implementarea algoritmului Bubble Sort

Mai jos este implementarea C ++ a algoritmului 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;
}

Ieșire:

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

Implementarea Python a algoritmului de sortare cu bule

Mai jos este implementarea Python a algoritmului 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)

Ieșire:

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

Legate de: Cum se folosește buclele în Python

C Implementarea algoritmului Bubble Sort

Mai jos este implementarea C a algoritmului 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;
}

Ieșire:

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

Implementarea JavaScript a algoritmului de sortare cu bule

Mai jos este implementarea JavaScript a algoritmului 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);

Ieșire:

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

Acum înțelegeți funcționarea algoritmului de sortare cu bule

Bubble Sort este cel mai simplu algoritm de sortare și este utilizat în principal pentru a înțelege bazele sortării. Bubble Sort poate fi, de asemenea, implementat recursiv, dar nu oferă avantaje suplimentare în acest sens.

Folosind Python, puteți implementa algoritmul Bubble Sort cu ușurință. Dacă nu sunteți familiarizați cu Python și doriți să începeți călătoria, a începe cu un script „Hello World” este o alegere excelentă.

Acțiune Acțiune Tweet E-mail Cum să începeți cu Python folosind un script „Hello World”

Python este unul dintre cele mai populare limbaje de programare utilizate astăzi. Urmați acest tutorial pentru a începe cu primul dvs. script Python.

Citiți în continuare
Subiecte asemănătoare
  • Programare
  • Java
  • Piton
  • Tutoriale de codare
Despre autor Yuvraj Chandra(60 de articole publicate)

Yuvraj este student la Universitatea din Delhi, India. Este pasionat de dezvoltarea web Full Stack. Când nu scrie, explorează profunzimea diferitelor tehnologii.

aplicații pe care puteți viziona filme
Mai multe de la Yuvraj Chandra

Aboneaza-te la newsletter-ul nostru

Alăturați-vă newsletter-ului pentru sfaturi tehnice, recenzii, cărți electronice gratuite și oferte exclusive!

Faceți clic aici pentru a vă abona