这次来说一下选择排序,与插入排序一样,选择排序在计算中数组也分为“已排序部分”和“未排序部分”。下面来说一下具体步骤,在初始状态中已排序部分的元素为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。