选择排序

本文深入探讨了选择排序算法的基本原理,对比了它与插入排序和冒泡排序的区别,并通过一道编程题展示了如何实现选择排序,同时计算并输出了交换操作的次数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这次来说一下选择排序,与插入排序一样,选择排序在计算中数组也分为“已排序部分”和“未排序部分”。下面来说一下具体步骤,在初始状态中已排序部分的元素为0个,所以假设最小元素下标min就等于0,然后将a[min]和之后的元素比较,遇到比a[min]小的则把它的下标给min。最后a[min]与首元素交换,这些步骤为第一轮排序。此后从第二个元素开始到末位再挑选最小元素的下标和其交换,以此类推,直到未排序部分的元素只剩一个了排序也就完成了(因为未排序部分的元素就剩一个那么最小的元素就是他自身)。
总之,选择排序和插入排序和冒泡排序的复杂度一样都是o(n^2),冒泡排序与选择排序相比,一个从局部入手减少逆序元素,一个放眼大局逐个选择最小值,二者思路不相同。但是,它们又都有着“通过i从外层循环,从数据中顺次求出i个最小值的相同特征”。相对地插入排序是通过i次外层循环,直接将原数组的i个元素重新排序。另外,不含flag的简单冒泡排序和选择排序不依赖数据,即比较运算的次数不受数据影响,而插入排序在执行时却依赖数据,处理相对有序的数据时会显得更加的高效。

下面来一道题目:
Write a program of the Selection Sort algorithm which sorts a sequence A in ascending order. The algorithm should be based on the following pseudocode:
SelectionSort(A)
1 for i = 0 to A.length-1
2 mini = i
3 for j = i to A.length-1
4 if A[j] < A[mini]
5 mini = j
6 swap A[i] and A[mini]
Note that, indices for array elements are based on 0-origin.
Your program should also print the number of swap operations defined in line 6 of the pseudocode in the case where i ≠ mini.
Input
The first line of the input includes an integer N, the number of elements in the sequence.
In the second line, N elements of the sequence are given separated by space characters.
Output
The output consists of 2 lines.
In the first line, please print the sorted sequence. Two contiguous elements of the sequence should be separated by a space character.
In the second line, please print the number of swap operations.
Constraints
1 ≤ N ≤ 100
Sample Input 1
6
5 6 4 2 1 3
Sample Output 1
1 2 3 4 5 6
4

Sample Input 2
6
5 2 4 6 1 3
Sample Output 2
1 2 3 4 5 6
3

#include<bits/stdc++.h>
using namespace std;
#define N 105

int ans;
void selectionsort(int arr[],int num)
{
	int i,j,min;
	ans = 0;
	for(i = 0;i < num - 1;i++)
	{
		min = i;
		for(j = i + 1;j < num;j++)
		{
			if(arr[j] < arr[min]) min = j;
		}
		if(min != i) ans++;
		swap(arr[min],arr[i]);
	}
}
int main()
{
	int a[N] = {0};
	int n;
	scanf("%d",&n); 
	for(int i = 0;i < n;i++) cin >> a[i];		
	selectionsort(a,n);
	for(int i = 0;i < n;i++)
	{
		if(i) cout << " ";
		cout << a[i];	
	}	
	cout << endl;
	cout << ans << endl; 
	return 0;
} 

这道题使用的就是选择排序的方法,在选择排序执行前我们需要将交换次数初始化为0,每交换一次交换次数就加1。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值