选择排序 (selection sort) 是一种简单直观的排序算法。它的工作原理如下:首先在未排序序列中找到最大(或最小)的元素,存放到排序序列的起始位置,然后,再从剩余未排序元素中继续寻找最大(或最小)元素,然后放到排序序列末尾。以此类推,直到所有元素均排序完毕。
伪代码
for i ( first element) to n (next to last element):
for i+1 (second element) to n(next to last element):
compare the i+1 element with nth element, if nth is greater, swap values
简单说明
- 交换操作介于0和(n − 1)次之间。
- 比较操作为n(n − 1) / 2次之间。
- 赋值操作介于0和3(n − 1)次之间。
源代码示例
/* 字符串指针排序函数 */
void stsrt (char *strings[], int num)
{
char *temp;
int top, seek;
for (top = 0; top < num-1; top++)
for (seek = top + 1; seek < num; seek++)
if (strcmp (strings[top], strings[seek]) > 0)
{
temp = strings[top];
strings[top] = strings[seek];
strings[seek] = temp;
}
}

