Úvod do algoritmu řazení bublin

Úvod do algoritmu řazení bublin

Třídění je jednou z nejzákladnějších operací, které můžete s daty použít. Prvky můžete třídit v různých programovacích jazycích pomocí různých třídicích algoritmů, jako je Rychlé třídění, Bublinové třídění, Sloučit třídění, Vkládací třídění atd. Řazení bublin je ze všech nejjednodušším algoritmem.





V tomto článku se dozvíte o fungování algoritmu Bubble Sort, pseudokódu algoritmu Bubble Sort, jeho časové a prostorové složitosti a jeho implementaci v různých programovacích jazycích, jako je C ++, Python, C a JavaScript.





Jak funguje algoritmus řazení bublin?

Bubble Sort je nejjednodušší třídící algoritmus, který opakovaně prochází seznamem, porovnává sousední prvky a vyměňuje je, pokud jsou ve špatném pořadí. Tento koncept lze efektivněji vysvětlit pomocí příkladu. Zvažte netříděné pole s následujícími prvky: {16, 12, 15, 13, 19}.





Příklad:

Zde jsou porovnávány sousední prvky a pokud nejsou ve vzestupném pořadí, jsou prohozeny.



Pseudokód algoritmu řazení bublin

V pseudokódu může být algoritmus Bubble Sort vyjádřen jako:

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

Výše uvedený algoritmus zpracovává všechna srovnání, i když je pole již seřazeno. Lze jej dále optimalizovat zastavením algoritmu, pokud vnitřní smyčka nezpůsobila žádnou výměnu. Tím se zkrátí doba provádění algoritmu.





Pseudokód optimalizovaného algoritmu Bubble Sort lze tedy vyjádřit jako:

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

Časová složitost a pomocný prostor algoritmu řazení bublin

Nejhorší časová složitost algoritmu řazení bublin je O (n^2). K tomu dochází, když je pole v sestupném pořadí a chcete jej řadit vzestupně nebo naopak.





kde je mikrofon na macbooku pro

Nejlepší časová složitost algoritmu řazení bublin je O (n). K tomu dochází, když je pole již seřazeno.

hraje ps5 hry ps4

Příbuzný: Co je Big-O notace?

Průměrná časová složitost algoritmu řazení bublin je O (n^2). K tomu dochází, když jsou prvky pole v neuspořádaném pořadí.

Pomocný prostor požadovaný pro algoritmus Bubble Sort je O (1).

C ++ Implementace algoritmu řazení bublin

Níže je implementace algoritmu Bubble Sort v C ++:

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

Výstup:

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

Implementace algoritmu Bubble Sort v Pythonu

Níže je implementace algoritmu Bubble Sort v Pythonu:

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

Výstup:

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

Příbuzný: Jak používat pro smyčky v Pythonu

C Implementace algoritmu řazení bublin

Níže je implementace C algoritmu 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;
}

Výstup:

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

Implementace JavaScriptu algoritmu řazení bublin

Níže je implementace JavaScriptu algoritmu 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);

Výstup:

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

Nyní rozumíte fungování algoritmu řazení bublin

Bubble Sort je nejjednodušší algoritmus řazení a používá se hlavně k pochopení základů třídění. Bubble Sort lze také implementovat rekurzivně, ale neposkytuje žádné další výhody.

Pomocí Pythonu můžete snadno implementovat algoritmus Bubble Sort. Pokud neznáte Python a chcete vyrazit na cestu, je skvělá volba začít skriptem „Hello World“.

Podíl Podíl tweet E-mailem Jak začít s Pythonem pomocí skriptu „Hello World“

Python je jedním z nejpopulárnějších programovacích jazyků, které se dnes používají. Pomocí tohoto tutoriálu můžete začít s prvním skriptem Pythonu.

Číst dále
Související témata
  • Programování
  • Jáva
  • Krajta
  • Návody na kódování
O autorovi Yuvraj Chandra(60 článků zveřejněno)

Yuvraj je studentem informatiky na univerzitě v Dillí v Indii. Je nadšený pro webový vývoj Full Stack. Když nepíše, zkoumá hloubku různých technologií.

proč můj netflix nefunguje
Více od Yuvraj Chandra

Přihlaste se k odběru našeho zpravodaje

Připojte se k našemu zpravodaji a získejte technické tipy, recenze, bezplatné elektronické knihy a exkluzivní nabídky!

Kliknutím sem se přihlásíte k odběru