記事のディレクトリ
このチュートリアルでは、選択ソートがどのように機能するかを学習します。さらに、選択ソートにCを使用した例があります。
選択的ソートは、各反復でソートされていないリストから最小の要素を選択し、その要素をソートされていないリストの先頭に配置するアルゴリズムです。
選択ソートはどのように機能しますか?
- 最初の要素を最小に設定します。
- 最小値を2番目の要素と比較します。2番目の要素が最小値よりも小さい場合、2番目の要素が最小値として指定されます。
最小要素と3番目の要素を比較します。同様に、3番目の要素が小さい場合は、3番目の要素を最小値として指定します。それ以外の場合は、何もしません。このプロセスは、最後の要素まで続きます。
- 各反復の後、最小値はソートされていないリストの先頭に配置されます。
- 反復ごとに、インデックスは最初のソートされていない要素から始まります。すべての要素が正しい位置に配置されるまで、手順1〜3を繰り返します。
ソートアルゴリズムを選択するための擬似コード
selectionSort(array, size)
repeat (size - 1) times
set the first unsorted element as the minimum
for each of the unsorted elements
if element < currentMinimum
set element as new minimum
swap minimum with first unsorted position
end selectionSort
Cの例
// Selection sort in C
#include <stdio.h>
// function to swap the the position of two elements
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
void selectionSort(int array[], int size) {
for (int step = 0; step < size - 1; step++) {
int min_idx = step;
for (int i = step + 1; i < size; i++) {
// To sort in descending order, change > to < in this line.
// Select the minimum element in each loop.
if (array[i] < array[min_idx])
min_idx = i;
}
// put min at the correct position
swap(&array[min_idx], &array[step]);
}
}
// function to print an array
void printArray(int array[], int size) {
for (int i = 0; i < size; ++i) {
printf("%d ", array[i]);
}
printf("\n");
}
// driver code
int main() {
int data[] = {
20, 12, 10, 15, 2};
int size = sizeof(data) / sizeof(data[0]);
selectionSort(data, size);
printf("Sorted array in Acsending Order:\n");
printArray(data, size);
}
複雑さ
サイクル | 比較の数 |
---|---|
初めて | (n-1) |
2回目 | (n-2) |
3回目 | (n-3) |
… | … |
前回 | 1 |
比較の数:(n-1)+(n-2)+(n-3)+…+ 1 = n(n-1)/ 2ほぼn2 n ^ 2に等しいn2。
複雑さ= O(n 2 n ^ 2n2)
さらに、サイクル数を観察するだけで複雑さを分析できます。2つのループがあるため、複雑さはn * n =n 2 n ^ 2です。n2。
時間計算量:
- 最悪の場合の複雑さ:O(n 2 n ^ 2n2)
昇順で並べ替え、配列を降順で並べ替えると、最悪のケースが発生します。 - 最良の場合の複雑さ:O(n 2 n ^ 2n2)
配列がソートされると表示されます - 平均的なケースの複雑さ:O(n 2 n ^ 2n2)
これは、配列の要素の順序が正しくない(昇順でも降順でもない)場合に発生します。
参照文書
[1]パレワラボPvt。Ltd.Selection Sort Algorithm [EB / OL] .https://www.programiz.com/dsa/selection-sort,2020-01-01。