目录
选择排序定义
选择排序(英语:Selection sort)是一种简单直观的排序算法。
简单来说,就是先求最小或最大值,将它放入新列表的最后端,循而往复,直到原数组为空时,停止,所以选择排序的最优时间复杂度、平均时间复杂度和最坏时间复杂度均为 O()。
代码
C++:
void selection_sort(int* a, int n)
{
for (int i = 1; i < n; ++i)
{
int ith = i;
for (int j = i + 1; j <= n; ++j)
{
if (a[j] < a[ith])
{
ith = j;
}
}
std::swap(a[i], a[ith]);
}
}
Python:
def selection_sort(a, n):
for i in range(1, n):
ith = i
for j in range(i + 1, n + 1):
if a[j] < a[ith]:
ith = j
a[i], a[ith] = a[ith], a[i]
Java:
// arr代码下标从 1 开始索引
static void selection_sort(int[] arr, int n)
{
for (int i = 1; i < n; i++)
{
int ith = i;
for (int j = i + 1; j <= n; j++)
{
if (arr[j] < arr[ith])
{
ith = j;
}
}
// swap
int temp = arr[i];
arr[i] = arr[ith];
arr[ith] = temp;
}
}
感谢:oi-wiki.org(参考文献)
2万+

被折叠的 条评论
为什么被折叠?



