C:C的排序算法:简单选择排序(SelectSort)

时间:2022-06-10 22:06:00
#include<stdio.h>
typedef struct Array{
	int key;
}Array;
#define LENGTH 10
void SelectSort(Array A[], int n);
void Swap(int *a,int *b);
int main() {
	int arr[LENGTH] = { 1,5,3,7,4,23,14,25,16,27 };
	int index = 1;
	Array A[LENGTH+1];
	while (index<=LENGTH) {
		A[index].key = arr[index - 1];
		printf("排序前:%d \n", A[index].key); 
		index++;
	}
	printf("***************\n");
	SelectSort(A,LENGTH);
	index = 1;
	while (index <= LENGTH) {
		printf("排序后:%d \n", A[index].key);
		index++;
	}
	getchar();
	return 0;
}
void Swap(int *A,int *B) {
	int temp;
	temp = *A;
	*A = *B;
	*B = temp;
}
void SelectSort(Array A[],int n) {
	int i,j,min;
	for (i = 0; i < n - 1; i++) {
		min = i;
		for (j = i + 1; j < n; j++) {
			if (A[j].key < A[min].key)
				min = j;
			if (min != i)
				Swap(&A[i].key, &A[min].key);
		}
	}
}