1. 程式人生 > >演算法實現:選擇排序(C/C++、Python)

演算法實現:選擇排序(C/C++、Python)

虛擬碼:

SELECTION-SORT{A)
n <- length[A]
for i<-1 to n-1 do
    j <-FIND-MIN(A,i,n)
    A[j]<->A[i]
end for

C/C++程式碼:

#include <stdio.h>
#include <string.h>
 
int main() {
	int n;
	int A[1000];
	int k = 0;
	while (scanf("%d", &n) != EOF) {
		A[k] = n;
		k++;
	}
	for (int i = 0; i < k - 1; i++) {
		for (int j = i + 1; j < k; j++) {
			if (A[j] < A[i]) {
				int temp = A[j];
				A[j] = A[i];
				A[i] = temp;
			}
		}
		for (int i = 0; i < k; i++)
			printf("%d ", A[i]);
		printf("\n");
		//列印每輪排序後的輸出,這樣看起來更清晰
	}
	printf("print the sorted number\n");
	for (int i = 0; i < k; i++)
		printf("%d ", A[i]);
	return 0;
}

執行結果如下:

1 7 6 4 2
^D
1 7 6 4 2 
1 2 7 6 4 
1 2 4 7 6 
1 2 4 6 7 
print the sorted number
1 2 4 6 7 
Process finished with exit code 0

Python3程式碼:

A = []
while True:
	try:
		A.append(int(input()))
	except:
		print('input complete')
		break
for i in range(len(A)):
	for j in range(len(A)):
		if j >= i + 1 and A[j] < A[i]:
			A[i], A[j] = A[j], A[i]
	for k in range(len(A)):
		print(A[k], end=' ')
	print('\n', end='')
# 列印每輪排序後的輸出,這樣看起來更清晰
print('print the sorted number')
for i in range(len(A)):
	print(A[i], end=' ')
# python3預設列印會換行,加上end='  ',則每次後面會自動加上' '中內容而不是換行

執行結果如下:

8
5
7
4
2
^D
input complete
2 8 7 5 4 
2 4 8 7 5 
2 4 5 8 7 
2 4 5 7 8 
2 4 5 7 8 
print the sorted number
2 4 5 7 8 
Process finished with exit code 0