Een inleiding tot het bellensorteeralgoritme

Een inleiding tot het bellensorteeralgoritme

Sorteren is een van de meest elementaire bewerkingen die u op gegevens kunt toepassen. U kunt elementen in verschillende programmeertalen sorteren met behulp van verschillende sorteeralgoritmen zoals Quick Sort, Bubble Sort, Merge Sort, Insertion Sort, enz. Bubble Sort is het meest eenvoudige algoritme van al deze.





In dit artikel leer je over de werking van het Bubble Sort-algoritme, de pseudocode van het Bubble Sort-algoritme, de complexiteit van tijd en ruimte en de implementatie ervan in verschillende programmeertalen zoals C++, Python, C en JavaScript.





Hoe werkt het bubbelsorteeralgoritme?

Bubble Sort is het eenvoudigste sorteeralgoritme dat herhaaldelijk door de lijst stapt, aangrenzende elementen vergelijkt en ze verwisselt als ze in de verkeerde volgorde staan. Dit concept kan efficiënter worden uitgelegd aan de hand van een voorbeeld. Beschouw een ongesorteerde array met de volgende elementen: {16, 12, 15, 13, 19}.





Voorbeeld:

Hier worden de aangrenzende elementen vergeleken en als ze niet in oplopende volgorde staan, worden ze verwisseld.



Pseudocode van het bellensorteeralgoritme

In pseudocode kan het Bubble Sort-algoritme worden uitgedrukt als:

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

Het bovenstaande algoritme verwerkt alle vergelijkingen, zelfs als de array al is gesorteerd. Het kan verder worden geoptimaliseerd door het algoritme te stoppen als de binnenste lus geen swap heeft veroorzaakt. Dit zal de uitvoeringstijd van het algoritme verkorten.





De pseudocode van het geoptimaliseerde Bubble Sort-algoritme kan dus worden uitgedrukt als:

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

Tijdcomplexiteit en hulpruimte van het belsorteeralgoritme

De tijdscomplexiteit in het slechtste geval van het Bubble Sort Algorithm is O(n^2). Het komt voor wanneer de array in aflopende volgorde staat en u deze in oplopende volgorde wilt sorteren of omgekeerd.





snelkoppeling om de computer in de slaapstand te zetten

De beste tijdscomplexiteit van het Bubble Sort Algorithm is O(n). Het treedt op wanneer de array al is gesorteerd.

hoe e-mailaccounts aan Gmail toe te voegen

Verwant: Wat is Big-O-notatie?

De gemiddelde tijdscomplexiteit van het Bubble Sort Algorithm is O(n^2). Het treedt op wanneer de elementen van de array in een door elkaar gegooide volgorde staan.

De hulpruimte die nodig is voor het Bubble Sort-algoritme is O(1).

C++ Implementatie van het Bubble Sort Algoritme

Hieronder staat de C++-implementatie van het Bubble Sort-algoritme:

// 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;
}

Uitgang:

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

Python-implementatie van het bellensorteeralgoritme

Hieronder staat de Python-implementatie van het Bubble Sort-algoritme:

# 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)

Uitgang:

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

Verwant: Hoe te gebruiken voor lussen in Python

C Implementatie van het bellensorteeralgoritme

Hieronder staat de C-implementatie van het Bubble Sort-algoritme:

// 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;
}

Uitgang:

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

JavaScript-implementatie van het bellensorteeralgoritme

Hieronder staat de JavaScript-implementatie van het Bubble Sort-algoritme:

// 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);

Uitgang:

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

Nu begrijp je de werking van het bellensorteeralgoritme

Bubble Sort is het eenvoudigste sorteeralgoritme en wordt voornamelijk gebruikt om de basis van sorteren te begrijpen. Bubble Sort kan ook recursief worden geïmplementeerd, maar biedt geen extra voordelen om dit te doen.

Met Python kunt u het Bubble Sort-algoritme gemakkelijk implementeren. Als je niet bekend bent met Python en je reis een kickstart wilt geven, is het een goede keuze om te beginnen met een 'Hello World'-script.

Deel Deel Tweeten E-mail Aan de slag met Python met een 'Hello World'-script

Python is een van de meest populaire programmeertalen die tegenwoordig wordt gebruikt. Volg deze tutorial om aan de slag te gaan met je allereerste Python-script.

Lees volgende
Gerelateerde onderwerpen
  • Programmeren
  • Java
  • Python
  • Codeerhandleidingen
Over de auteur Yuvraj Chandra(60 artikelen gepubliceerd)

Yuvraj is een student Computerwetenschappen aan de Universiteit van Delhi, India. Hij is gepassioneerd door Full Stack Web Development. Als hij niet aan het schrijven is, onderzoekt hij de diepte van verschillende technologieën.

hoe je in een handomdraai kunt sssen zonder dat ze het weten
Meer van Yuvraj Chandra

Abonneer op onze nieuwsbrief

Word lid van onze nieuwsbrief voor technische tips, recensies, gratis e-boeken en exclusieve deals!

Klik hier om je te abonneren