C:C的排序算法:直接插入排序(InsertSort)

#include
typedef struct A{
	int key;
}A;
void InsertSort(A K[], int n){
	int i, j;
	for (i = 2; i <= n; i++) {
		if (K[i].key < K[i - 1].key) {
			K[0] = K[i];
			for (j = i - 1; K[0].key < K[j].key; --j) {
				K[j + 1] = K[j];
			}
			K[j + 1] = K[0];
		}
	}
}
void main() {
	int Array[5] = { 1,5,2,7,4 };
	A K[6];
	int size = sizeof(Array) / sizeof(Array[0]);
	K[0].key = size;
	int i = 1;
	while (i<=5) {
		K[i].key = Array[i-1];
		printf("K[%d].key:%d\n", i, K[i].key);
		i++;
	}
	printf("length:%d\n", K[0].key);
	InsertSort(K, K[0].key); 
	i = 0;
	while (i <= size) {
		printf("K[%d].key:%d\n", i, K[i].key);
		i++;
	}
	getchar();
}

你可能感兴趣的:(C)