前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Selection Sort

Selection Sort

作者头像
废江_小江
发布2022-09-05 13:18:16
3720
发布2022-09-05 13:18:16
举报
文章被收录于专栏:总栏目

Question

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:

代码语言:javascript
复制
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

Meaning

实现选择排序的过程,并且输出选择排序过程中的排序次数

Solution

简单选择排序,每次在第二层无序区中找出一个最小的数,放到第一层的下标i处。但是小标i也有可能是最小的数,所以也要来进行比较。

Coding

代码语言:javascript
复制
#include<iostream>
using namespace std;
void SelectionSort(int a[], int n ,int &sum) {
	int i, j, min;
	for ( i = 0; i < n-1; i++) {
		//第一层循环为无序区
		min = i;//k记录当前的下标,到时需要交换
		for ( j = i + 1; j < n; j++) {
			//第二层循环为有序区
			if (a[j] < a[min])
				min = j; //此时min便是最小的数
		}
		if (min != i) {
			//为了防止最小数有两个,即最外层for循环i是最小数,无序区也有一个最小数,这样交换过来排序便不再稳定
			swap(a[min], a[i]);
			sum++;
		}
	}
}
void Print(int a[], int n) {
	for (int i = 0; i < n; i++) {
		if (i > 0) cout << " ";
		cout << a[i];
	}
}
int main() {
	int n, sum = 0;
	cin >> n;
	int a[105];
	for (int i = 0; i < n; i++)
		cin >> a[i];
	SelectionSort(a, n, sum);
	Print(a, n);
	cout << endl << sum << endl;
}

Summary

插入排序能够较快的处理相对有序的数据,冒泡排序中的交换次数可以体现数列的错乱程度,

废江博客 , 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权

转载请注明原文链接:Selection Sort

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020-03-28),如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Question
  • Meaning
  • Solution
  • Coding
  • Summary
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档