バブルソート
バブルソート手法の複雑さ
- 時間計算量: 最良の場合はO(n)、平均および最悪の場合はO(n ^ 2)
- スペースの複雑さ: O(1)
入力と出力
Input: A list of unsorted data: 56 98 78 12 30 51 Output: Array after Sorting: 12 30 51 56 78 98
アルゴリズム
bubbleSort( array, size)
入力- データの配列、および配列内の総数
出力- ソートされた配列
Begin for i := 0 to size-1 do flag := 0; for j:= 0 to size –i – 1 do if array[j] > array[j+1] then swap array[j] with array[j+1] flag := 1 done if flag ≠ 1 then break the loop. done End
例
#include<iostream>
using namespace std;
void swapping(int &a, int &b) { //swap the content of a and b
int temp;
temp = a;
a = b;
b = temp;
}
void display(int *array, int size) {
for(int i = 0; i<size; i++)
cout << array[i] << " ";
cout << endl;
}
void bubbleSort(int *array, int size) {
for(int i = 0; i<size; i++) {
int swaps = 0; //flag to detect any swap is there or not
for(int j = 0; j<size-i-1; j++) {
if(array[j] > array[j+1]) { //when the current item is bigger than next
swapping(array[j], array[j+1]);
swaps = 1; //set swap flag
}
}
if(!swaps)
break; // No swap in this pass, so array is sorted
}
}
int main() {
int n;
cout << "Enter the number of elements: ";
cin >> n;
int arr[n]; //create an array with given number of elements
cout << "Enter elements:" << endl;
for(int i = 0; i<n; i++) {
cin >> arr[i];
}
cout << "Array before Sorting: ";
display(arr, n);
bubbleSort(arr, n);
cout << "Array after Sorting: ";
display(arr, n);
} 出力
Enter the number of elements: 6 Enter elements: 56 98 78 12 30 51 Array before Sorting: 56 98 78 12 30 51 Array after Sorting: 12 30 51 56 78 98
-
KeyValuePairsをC#で並べ替える
Sortメソッドを使用して、KeyValuePairsコレクションを並べ替えます。 まず、コレクションを設定します- var myList = new List<KeyValuePair<int, int>>(); // adding elements myList.Add(new KeyValuePair<int, int>(1, 20)); myList.Add(new KeyValuePair<int, int>(2, 15)); myList.Add(new KeyValuePair<int, int>(3, 35));
-
C#のバブルソートプログラム
バブルソートは単純なソートアルゴリズムです。この並べ替えアルゴリズムは比較ベースのアルゴリズムであり、隣接する要素の各ペアが比較され、要素が順番に並んでいない場合は要素が交換されます。 intに5つの要素があるとしましょう- int[] arr = { 78, 55, 45, 98, 13 }; それでは、バブルソートを実行しましょう。 最初の2つの要素78と55から始めます。55は78より小さいので、両方を交換します。これでリストは-になります 55, 78,45,98, 13 現在、45は78未満なので、交換してください。 55, 45, 78, 98, 3 現在、98は78より大き