Selection Sort
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
分析
实现一个选择排序,并记录比较的次数
代码
#pragma warning(disable:4996)
#include<stdio.h>
#include<iostream>
void trace(int a[], int n) {
for (int i = 0; i < n; i++) {
if (i != 0) {
printf(" ");
}
printf("%d", a[i]);
}
printf("\n");
}
int selectSort(int a[], int n) {
int min ,num=0,tag;//num记录交换次数
for (int i = 0; i < n; i++) {
int k = -1;//记录最小值的位置
tag = 0;//标记a[i]是否是最小值,决定是否发生交换
min = a[i];//记录最小值,默认是当前的a[i]
for (int j = i; j < n; j++) {
if (min > a[j]) {
min = a[j];
k = j;
tag = 1;
}
}
if (tag) {//如果a[i]不是min,则交换之
int temp = a[i];
a[i] = a[k];
a[k] = temp;
//trace(a,n);
num++;
}
}
return num;
}
int main() {
int n, i, j;
int a[100];
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%d", &a[i]);
}
int m = selectSort(a, n);
trace(a, n);
printf("%d\n", m);
return 0;
}
书上代码
#pragma warning(disable:4996)
#include<stdio.h>
int selectionSort(int A[], int N) {
int i, j, t, sw = 0, minj;
for (i = 0; i < N - 1; i++) {
minj = i;
for (j = i; j < N; j++) {
if (A[j] < A[minj]) minj = j;
}
t = A[i];
A[i] = A[minj];
A[minj] = t;
if (i != minj) sw++;
}
return sw;
}
int main() {
int A[100], N, i, sw;
scanf("%d", &N);
for (int i = 0; i < N; i++) {
scanf("%d", &A[i]);
}
sw = selectionSort(A, N);
for (i = 0; i < N; i++) {
if (i > 0) printf(" ");
printf("%d", A[i]);
}
printf("\n%d\n", sw);
/*getchar();
getchar();*/
return 0;
}
思路
没什么好说的,一样的思路,唯一区别的地方在于,i 只遍历到了倒数第二个,因为遍历前n-1个最小值都找到了他最终的位置,最后一个必然也在他最终的位置上