C:C的排序算法:冒泡排序(BubbleSort)

#include
typedef struct Array{
	int key;
}Array;
typedef enum {
	false,
	true
}bool;
#define LENGTH 10  //排序元素个数
void BubbleSort(Array A[],int n);
void swap(int *A,int *B);
void main() {
	int Arr[LENGTH] = { 2,5,1,6,3,12,2141,2423,232,252 };
	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");
	BubbleSort(A,LENGTH);
	index = 1;
	while (index <= LENGTH){
		printf("排序后:%d\n", A[index].key);
		index++;
	}
	getchar();
}
void swap(int *A, int *B) {
	int temp;
	temp = *A;
	*A = *B;
	*B = temp;
}
void BubbleSort(Array A[],int n) {
	int i, j;
	bool flag;
	for (i = 1; i <= n; i++) {
		flag = false;
		for (j = n; j > i; j--) {
			if (A[j].key < A[j - 1].key) {
				swap(&A[j].key,&A[j-1].key);
				flag = true;
			}
		}
		if (flag = false)
			return;
	}
}

你可能感兴趣的:(C)