並べ替えは、データに適用できる最も基本的な操作の1つです。クイックソート、バブルソート、マージソート、挿入ソートなどのさまざまなソートアルゴリズムを使用して、さまざまなプログラミング言語で要素をソートできます。バブルソートは、これらすべての中で最も単純なアルゴリズムです。
この記事では、バブルソートアルゴリズムの動作、バブルソートアルゴリズムの擬似コード、時間と空間の複雑さ、およびC ++、Python、C、JavaScriptなどのさまざまなプログラミング言語での実装について学習します。
バブルソートアルゴリズムはどのように機能しますか?
バブルソートは、リストを繰り返しステップ実行し、隣接する要素を比較し、順序が間違っている場合はそれらを交換する最も単純なソートアルゴリズムです。この概念は、例を使用してより効率的に説明できます。次の要素を持つソートされていない配列について考えてみます:{16、12、15、13、19}。
例:
ここでは、隣接する要素が比較され、昇順でない場合は交換されます。
バブルソートアルゴリズムの擬似コード
擬似コードでは、バブルソートアルゴリズムは次のように表すことができます。
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
上記のアルゴリズムは、配列がすでにソートされている場合でも、すべての比較を処理します。内部ループによってスワップが発生しなかった場合は、アルゴリズムを停止することで、さらに最適化できます。これにより、アルゴリズムの実行時間が短縮されます。
したがって、最適化されたバブルソートアルゴリズムの擬似コードは次のように表すことができます。
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
バブルソートアルゴリズムの時間計算量と補助空間
バブルソートアルゴリズムの最悪の場合の時間計算量はO(n ^ 2)です。これは、配列が降順であり、昇順で並べ替える場合、またはその逆の場合に発生します。
USBポートが機能していません
バブルソートアルゴリズムの最良の時間計算量はO(n)です。配列がすでにソートされている場合に発生します。
.jarファイルウィンドウを開く10
関連している: Big-O表記とは何ですか?
バブルソートアルゴリズムの平均的な時間計算量はO(n ^ 2)です。これは、配列の要素が乱雑な順序になっている場合に発生します。
バブルソートアルゴリズムに必要な補助スペースはO(1)です。
バブルソートアルゴリズムのC ++実装
以下は、バブルソートアルゴリズムの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;
}
出力:
Unsorted Array:
16 12 15 13 19
Sorted Array in Ascending Order:
12 13 15 16 19
バブルソートアルゴリズムのPython実装
以下は、バブルソートアルゴリズムのPython実装です。
# 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)
出力:
Unsorted List:
16 12 15 13 19
Sorted List in Ascending Order:
12 13 15 16 19
関連している: PythonでForループを使用する方法
Cバブルソートアルゴリズムの実装
以下は、バブルソートアルゴリズムのC実装です。
// 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;
}
出力:
Unsorted Array:
16 12 15 13 19
Sorted Array in Ascending Order:
12 13 15 16 19
バブルソートアルゴリズムのJavaScript実装
以下は、バブルソートアルゴリズムのJavaScript実装です。
// 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);
出力:
Unsorted Array:
16 12 15 13 19
Sorted Array in Ascending Order:
12 15 13 16 19
これで、バブルソートアルゴリズムの動作を理解できました
バブルソートは最も単純なソートアルゴリズムであり、主にソートの基礎を理解するために使用されます。バブルソートは再帰的に実装することもできますが、そうすることによる追加の利点はありません。
Pythonを使用すると、バブルソートアルゴリズムを簡単に実装できます。 Pythonに慣れておらず、旅を始めたい場合は、「HelloWorld」スクリプトから始めるのが最適です。
共有 共有 つぶやき Eメール 'HelloWorld'スクリプトを使用してPythonを使い始める方法Pythonは、今日使用されている最も人気のあるプログラミング言語の1つです。このチュートリアルに従って、最初のPythonスクリプトを開始してください。
次を読む 関連トピック- プログラミング
- Java
- Python
- コーディングチュートリアル
Yuvrajは、インドのデリー大学のコンピュータサイエンス学部生です。彼はフルスタックWeb開発に情熱を注いでいます。執筆していないときは、さまざまなテクノロジーの深さを探っています。
あなたのブログを人気にする方法YuvrajChandraのその他の作品
ニュースレターを購読する
ニュースレターに参加して、技術的なヒント、レビュー、無料の電子書籍、限定セールを入手してください。
購読するにはここをクリックしてください