1. 程式人生 > >排序方法6---簡單選擇排序

排序方法6---簡單選擇排序

#include<stdio.h>
#include<iostream>
#define MAXL 100
typedef int KeyType;
typedef char InfoType;
typedef struct
{
	KeyType key;
	InfoType data;
}RecType;
void swap(RecType &x, RecType &y)
{
	RecType temp;
	temp = x;
	x = y;
	y = temp;
}
void CreateList(RecType R[], KeyType keys[
], int n) { for (int i = 0; i < n; i++) { R[i].key = keys[i]; } } void Display(RecType R[], int n) { for (int i = 0; i < n; i++) { printf("%d", R[i].key); } printf("\n"); } void SelectSort(RecType R[], int n) { int i, j, k; RecType temp; for (i = 0; i<n - 1; i++) //做第i趟排序 { k =
i; for (j = i + 1; j<n; j++) //在當前無序區R[i..n-1]中選key最小的R[k] if (R[j].key<R[k].key) k = j; //k記下目前找到的最小關鍵字所在的位置 if (k != i) //交換R[i]和R[k] swap(R[i],R[k]); printf(" i=%d: ,選擇關鍵字:%d, 排序結果為:", i,R[i].key); Display(R, n); } } int main() { int n = 10; RecType R[
MAXL]; KeyType a[] = { 9,8,7,6,5,4,3,2,1,0 }; CreateList(R, a, n); printf("排序前:"); Display(R, n); SelectSort(R, n); printf("排序後:"); Display(R, n); system("pause"); return 1; }

在這裡插入圖片描述