Johdanto kuplalajittelualgoritmiin

Johdanto kuplalajittelualgoritmiin

Lajittelu on yksi perustoiminnoista, joita voit käyttää tietoihin. Voit lajitella elementtejä eri ohjelmointikielillä käyttämällä erilaisia ​​lajittelualgoritmeja, kuten Quick Sort, Bubble Sort, Merge Sort, Insertion Sort jne. Bubble Sort on yksinkertaisin algoritmi kaikkien näiden joukossa.





Tässä artikkelissa opit Bubble Sort -algoritmin toiminnasta, Bubble Sort -algoritmin pseudokoodista, sen aika- ja avaruuden monimutkaisuudesta ja sen toteutuksesta eri ohjelmointikielillä, kuten C ++, Python, C ja JavaScript.





Miten kuplalajittelualgoritmi toimii?

Bubble Sort on yksinkertaisin lajittelualgoritmi, joka toistuvasti selaa luetteloa, vertaa vierekkäisiä elementtejä ja vaihtaa ne, jos ne ovat väärässä järjestyksessä. Tämä käsite voidaan selittää tehokkaammin esimerkin avulla. Harkitse lajittelematonta taulukkoa, jossa on seuraavat elementit: {16, 12, 15, 13, 19}.





Esimerkki:

Tässä vierekkäisiä elementtejä verrataan ja jos ne eivät ole nousevassa järjestyksessä, ne vaihdetaan.



Kuplan lajittelualgoritmin pseudokoodi

Pseudokoodissa Bubble Sort -algoritmi voidaan ilmaista seuraavasti:

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

Yllä oleva algoritmi käsittelee kaikki vertailut, vaikka taulukko on jo lajiteltu. Sitä voidaan optimoida edelleen pysäyttämällä algoritmi, jos sisäinen silmukka ei aiheuttanut vaihtoa. Tämä lyhentää algoritmin suoritusaikaa.





Siten optimoidun kuplalajittelualgoritmin pseudokoodi voidaan ilmaista seuraavasti:

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

Kuplan lajittelualgoritmin aika monimutkaisuus ja aputila

Kuplan lajittelualgoritmin pahimman ajan monimutkaisuus on O (n^2). Se tapahtuu, kun taulukko on laskevassa järjestyksessä ja haluat lajitella sen nousevaan järjestykseen tai päinvastoin.





miten voin ladata youtube -videoita iPhoneeni

Kuplan lajittelualgoritmin paras monimutkaisuus on O (n). Se tapahtuu, kun taulukko on jo lajiteltu.

kuinka siirtää sovelluksia puhelimesta SD -kortille

Aiheeseen liittyviä: Mikä on Big-O-merkintä?

Bubble Sort Algoritmin keskimääräisen tapauksen monimutkaisuus on O (n^2). Se tapahtuu, kun taulukon elementit ovat sekavassa järjestyksessä.

Bubble Sort -algoritmin tarvitsema lisätila on O (1).

C ++ Bubble Sort Algoritmin toteuttaminen

Alla on Bubble Sort -algoritmin C ++ -toteutus:

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

Lähtö:

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

Kuplan lajittelualgoritmin Python -toteutus

Alla on Bubble Sort -algoritmin Python -toteutus:

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

Lähtö:

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

Aiheeseen liittyviä: Kuinka käyttää silmukoita Pythonissa

C Bubble Sort Algoritmin toteuttaminen

Alla on B -kuplalajittelualgoritmin C -toteutus:

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

Lähtö:

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

Kuplan lajittelualgoritmin JavaScript -toteutus

Alla on Bubble Sort -algoritmin JavaScript -toteutus:

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

Lähtö:

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

Nyt ymmärrät kuplalajittelualgoritmin toiminnan

Bubble Sort on yksinkertaisin lajittelualgoritmi, ja sitä käytetään pääasiassa lajittelun perusteiden ymmärtämiseen. Bubble Sort voidaan toteuttaa myös rekursiivisesti, mutta se ei tarjoa lisäetuja.

Pythonin avulla voit toteuttaa Bubble Sort -algoritmin helposti. Jos et tunne Pythonia ja haluat aloittaa matkan, aloita Hello World -skriptillä aloittaminen.

Jaa Jaa Tweet Sähköposti Pythonin käytön aloittaminen Hello World -skriptin avulla

Python on yksi suosituimmista ohjelmointikielistä. Noudata tätä opetusohjelmaa aloittaaksesi ensimmäisen Python -komentosarjasi.

Lue seuraava
Liittyvät aiheet
  • Ohjelmointi
  • Java
  • Python
  • Koodausoppaat
Kirjailijasta Yuvraj Chandra(60 artikkelia julkaistu)

Yuvraj on tietojenkäsittelytieteen perusopiskelija Delhin yliopistossa Intiassa. Hän on intohimoinen Full Stack Web -kehityksestä. Kun hän ei kirjoita, hän tutkii eri tekniikoiden syvyyttä.

seuranta (kaupallinen lentoyhtiö)
Lisää Yuvraj Chandralta

tilaa uutiskirjeemme

Liity uutiskirjeeseemme saadaksesi teknisiä vinkkejä, arvosteluja, ilmaisia ​​e -kirjoja ja ainutlaatuisia tarjouksia!

Klikkaa tästä tilataksesi