排序算法:选择排序

八月 15th, 2010, in 程序人生, by None
选择排序 (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; } }

发表回复

您的 email 地址不会被公开。 必填信息前已经标志为 *

*

您可以使用这些 HTML 标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>