选择排序

算法导论中练习题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.length
for i=1 to n-1
	// 找出A[i+1, i+2, ..., n]中最小元素并与A[i]交换
	key = A[i]
	for j=i+1 to n
		if ( A[j]<key )
			A[i] = A[j]
			A[j] = key
			key = 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 sort
	for (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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值