选择排序

题目:
Consider sorting n numbers in an array A by first finding the smallest element of A and exchanging it with the element in A[1]. Then find the second smallest element of A, and exchange it with A[2]. Continue in this manner for the first n−1 elements of A. Write pseudocode for this algorithm, which is known as selection sort. What loop invariants 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 the worst-case running times of selection sort in Θ-notation.

伪代码:

SELECTION-SORT(A):
  for i = 1 to A.length - 1
      min = i
      for j = i + 1 to A.length
          if A[j] < A[min]
              min = j
      temp = A[i]
      A[i] = A[min]
      A[min] = temp

循环不变式

在外部for循环的每次迭代开始时, A [ 1 … i - 1 ]包含数组中最小的i- 1元素,按非递减顺序排序。
在内部for循环的每次迭代开始时, A [min]是A[i…j - 1]中最小的数;

时间复杂度

Θ(n2) .

代码:

#include <iostream>
#include <vector>
#include <ctime>
using namespace std;
void search_sort(int *a){
	int i;
	for(i = 1;i <= 10;i++)
	{
		int min = i;
		for(int j = i+1;j < 10;j++)
		{
			if(a[j] <a[min])
			{
				min = j;
			}
		}
		int tmp;
		tmp = a[i] ;
		a[i] = a[min];
		a[min] = tmp;
	}
	
	for(int i = 0;i<10;i++)
	{
		cout<<a[i]<<endl;
	}
	cout<<endl;
}
int main()
{
	int a[10]={1,2,15,9,10,2,4,7,4,9};
	for(int i = 0;i<10;i++)
	{
		cout<<a[i] <<endl;
	}
	search_sort(a);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值