バケットソート
バケットソート手法では、データ項目はバケットのセットに分散されます。各バケットは、同様のタイプのデータを保持できます。配布後、各バケットは別の並べ替えアルゴリズムを使用して並べ替えられます。その後、すべての要素がメインリストに集められ、並べ替えられたフォームが取得されます。
バケットソート手法の複雑さ
-
時間計算量:最良の場合と平均的な場合はO(n + k)、最悪の場合はO(n ^ 2)。
-
スペースの複雑さ:最悪の場合のO(nk)
入力と出力
Input: A list of unsorted data: 0.25 0.36 0.58 0.41 0.29 0.22 0.45 0.79 0.01 0.69 Array before Sorting: 0.25 0.36 0.58 0.41 0.29 0.22 0.45 0.79 0.01 0.69 Output: Array after Sorting: 0.01 0.22 0.25 0.29 0.36 0.41 0.45 0.58 0.69 0.79
アルゴリズム
bucketSort(array, size)
入力- データの配列、および配列内の総数
出力- ソートされた配列
Begin for i := 0 to size-1 do insert array[i] into the bucket index (size * array[i]) done for i := 0 to size-1 do sort bucket[i] done for i := 0 to size -1 do gather items of bucket[i] and put in array done End
例
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
void display(float *array, int size) {
for(int i = 0; i<size; i++)
cout << array[i] << " ";
cout << endl;
}
void bucketSort(float *array, int size) {
vector<float> bucket[size];
for(int i = 0; i<size; i++) { //put elements into different buckets
bucket[int(size*array[i])].push_back(array[i]);
}
for(int i = 0; i<size; i++) {
sort(bucket[i].begin(), bucket[i].end()); //sort individual vectors
}
int index = 0;
for(int i = 0; i<size; i++) {
while(!bucket[i].empty()) {
array[index++] = *(bucket[i].begin());
bucket[i].erase(bucket[i].begin());
}
}
}
int main() {
int n;
cout << "Enter the number of elements: ";
cin >> n;
float 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);
bucketSort(arr, n);
cout << "Array after Sorting: ";
display(arr, n);
} 出力
Enter the number of elements: 10 Enter elements: 0.25 0.36 0.58 0.41 0.29 0.22 0.45 0.79 0.01 0.69 Array before Sorting: 0.25 0.36 0.58 0.41 0.29 0.22 0.45 0.79 0.01 0.69 Array after Sorting: 0.01 0.22 0.25 0.29 0.36 0.41 0.45 0.58 0.69 0.79
-
JavaScriptのArray.prototype.sort()。
JavaScript Array.prototype.sort()メソッドは、配列の並べ替えに使用されます。並べ替えの順序は、アルファベット、数字、昇順、降順のいずれかです。 以下は、Array.prototype.sort()メソッドのコードです- 例 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-
-
Androidで配列要素を並べ替える方法は?
この例は、Androidで配列要素を並べ替える方法を示しています。 ステップ1 − Android Studioで新しいプロジェクトを作成し、[ファイル]⇒[新しいプロジェクト]に移動して、新しいプロジェクトを作成するために必要なすべての詳細を入力します。 ステップ2 −次のコードをres / layout/activity_main.xmlに追加します。 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://schemas.a