选择排序

来源:互联网 发布:java 文件读取 编辑:程序博客网 时间:2024/06/06 03:37

算法导论中练习题2.2-2

考虑排序储存在数组A中的n个数:首先找出A中的最小元素并将其与A[1]中的元素进行交换。

接着,找出A中的次小元素将其与A[2]中元素进行交换。对A中前n-1个元素按该方式继续。

该算法为选择排序。写出起伪代码


英文版(考虑到可能翻译的不到位,所以把英文原文贴上):

Consider sorting n numbers stored in array A by first finding the smallest element

of A and exchanging it with the element in AOE1. Then find the second smallest
element of A, and exchange it with AOE2. Continue in this manner for the first n1
elements of A. Write pseudocode for this algorithm, which is known as selection
sort. What loop invariant does this algorithm maintain? Why does it need to run
for only the first n  1 elements, rather than for all n elements? Give the best-case

and worst-case running times of selection sort in ‚-notation.


伪代码如下:

n = A.lengthfor i=1 to n-1// 找出A[i+1, i+2, ..., n]中最小元素并与A[i]交换key = A[i]for j=i+1 to nif ( A[j]<key )A[i] = A[j]A[j] = keykey = A[i]


最好情况用时 T(n) =  n 平方

最坏情况用时 T(n) = n 平方



C语言代码如下:

#include <stdio.h>int main(void){int A[] = { 34, 25, 78, 12, 93, 40, 19 };int i, j, key, n;n = sizeof(A)/sizeof(int);printf("n=%d\n", n);printf("before select sort A[] is:");// print array A[]for (i = 0; i < n; ++i) {printf("%d ", A[i]);}printf("\n");// select sortfor (i = 0; i <= n-2; ++i) {// find the min element in A[i+1,i+2, ..., n] and exchange it with A[i]key = A[i];for (j = i+1; j <= n-1; ++j) {if (A[j] < key) {A[i] = A[j];A[j] = key;key = A[i];}}}// print array A[]printf("after select sort A[] is:");for (i = 0; i < n; ++i) {printf("%d ", A[i]);}printf("\n");    return 0;}


0 0
原创粉丝点击