文章目录
在本教程中,您将学习选择排序的工作方式。此外,您还将找到使用C进行选择排序的示例。
选择排序是一种算法,它在每次迭代中从未排序的列表中选择最小的元素,并将该元素放在未排序列表的开头。
选择排序如何工作?
- 将第一个元素设置为 minimum。
- 将 minimum 与第二个元素进行比较。如果第二个元素小于 minimum,则将第二个元素指定为 minimum。
比较 minimum 和第三个元素。同样,如果第三个元素较小,则将第三个元素指定为 minimum ,否则什么也不做。这个过程一直持续到最后一个元素。
- 在每次迭代之后, minimum 被放在未排序列表的前面。
- 对于每次迭代,索引从第一个未排序的元素开始。重复步骤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) |
第二次 | (n-2) |
第三次 | (n-3) |
… | … |
最后一次 | 1 |
比较次数:(n - 1) + (n - 2) + (n - 3) + … + 1 = n(n - 1) / 2 约等于 n 2 n^2 n2。
复杂度=O( n 2 n^2 n2)
此外,我们可以通过简单地观察循环的次数来分析复杂性。有2个循环,所以复杂度是n*n= n 2 n^2 n2。
时间复杂度:
- 最坏情况复杂度:O( n 2 n^2 n2)
如果我们想按升序排序,而数组按降序排序,则会出现最坏的情况。 - 最佳情况复杂度:O( n 2 n^2 n2)
出现在数组已排好序的情况下 - 平均情况复杂度:O( n 2 n^2 n2)
当数组的元素顺序混乱(既不是升序也不是降序)时,就会发生这种情况。
参考文档
[1]Parewa Labs Pvt. Ltd.Selection Sort Algorithm[EB/OL].https://www.programiz.com/dsa/selection-sort,2020-01-01.