与えられた複雑さの制約でクイックソートを実装するC++プログラム
クイックソートは分割統治法に基づいています。このアルゴリズムの平均時間計算量はO(n * log(n))ですが、最悪の場合の複雑さはO(n ^ 2)です。ここで最悪のケースの可能性を減らすために、クイックソートはランダム化を使用して実装されています。
アルゴリズム
partition(int a []、int l、int h)
Begin pivot = h Index = l start = l and end = h while start < end do while a[start] <= pivot AND start < end do start = start +1 done while a[end] > pivot do end = end – 1 done if start < end then swap a[start] with a[end] done a[low] = a[end] a[end] = pivot return end End
RandomPivotPartition(int a []、int l、int h)
Begin n = rand() pivot = l + n%(h-l+1); Swap a[h] with a[pivot] return Partition(a, l, h) End
QuickSort(int a []、int l、int h)
Begin int pindex; If (l<h) pindex = RandomPivotPartition(a, l, h) QuickSort(a, l, pindex-1) QuickSort(a, pindex+1, h) return 0 End
サンプルコード
#include<iostream>
#include<cstdlib>
using namespace std;
void swap(int *a, int *b) {
int temp;
temp = *a;
*a = *b;
*b = temp;
}
int Partition(int a[], int l, int h) {
int pivot, index, i;
index = l;
pivot = h;
for(i = l; i < h; i++) {
if(a[i] < a[pivot]) {
swap(&a[i], &a[index]);
index++;
}
}
swap(&a[pivot], &a[index]);
return index;
}
int RandomPivotPartition(int a[], int l, int h) {
int pvt, n, temp;
n = rand();
pvt = l + n%(h-l+1);
swap(&a[h], &a[pvt]);
return Partition(a, l, h);
}
int QuickSort(int a[], int l, int h) {
int pindex;
if(l < h) {
pindex = RandomPivotPartition(a, l, h);
QuickSort(a, l, pindex-1);
QuickSort(a, pindex+1, h);
}
return 0;
}
int main() {
int n, i;
cout<<"\nEnter the number of data element to be sorted: ";
cin>>n;
int arr[n];
for(i = 0; i < n; i++) {
cout<<"Enter element "<<i+1<<": ";
cin>>arr[i];
}
QuickSort(arr, 0, n-1);
cout<<"\nSorted Data ";
for (i = 0; i < n; i++)
cout<<"->"<<arr[i];
return 0;
} 出力
Enter the number of data element to be sorted: 4 Enter element 1: 3 Enter element 2: 4 Enter element 3: 7 Enter element 4: 6 Sorted Data ->3->4->6->7
-
バケットソートを実装するC++プログラム
バケットソート手法では、データ項目はバケットのセットに分散されます。各バケットは、同様のタイプのデータを保持できます。配布後、各バケットは別の並べ替えアルゴリズムを使用して並べ替えられます。その後、すべての要素がメインリストに集められ、並べ替えられたフォームが取得されます。 バケットソート手法の複雑さ 時間計算量:最良の場合と平均的な場合はO(n + k)、最悪の場合はO(n2)。 スペースの複雑さ:最悪の場合のO(nk) Input − A list of unsorted data: 0.25 0.36 0.58 0.41 0.29 0.22 0.45 0.79
-
基数ソートを実装するC++プログラム
基数ソートは、非比較ソートアルゴリズムです。この並べ替えアルゴリズムは、同じ位置と値を共有する数字をグループ化することにより、整数キーで機能します。基数は、記数法のベースです。 10進法では、基数または基数は10であることがわかっているので、いくつかの10進数を並べ替えるには、数値を格納するために10個の位取りボックスが必要です。 基数ソート手法の複雑さ 時間計算量:O(nk) スペースの複雑さ:O(n + k) Input − The unsorted list: 802 630 20 745 52 300 612 932 78 187 Output &minus