0057.起泡排序(Bubble Sort)C语言实例
数据结构与算法 2021年5月30日
#include <stdio.h>
#include <stdlib.h>
#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
#define MAXSIZE 20
typedef int Status;
typedef int KeyType;
typedef int InfoType;
typedef struct {
KeyType key;
InfoType otherinfo;
}RedType;
typedef struct {
RedType r[MAXSIZE+1];
int length;
}SqList;
Status ListInsert(SqList *L)
{
int i, n;
printf("Input number of key: ");
scanf("%d", &n);
if(n>MAXSIZE)
exit(-1);
L->r[0].key = 0;
L->length = 0;
for(i=1; i<=n; i++)
{
printf("Input key: ");
scanf("%d", &L->r[i]);
L->length++;
}
return OK;
}
void ListTraverse(SqList L)
{
int i;
for(i=1; i<=L.length; i++)
printf("%d ", L.r[i].key);
printf("\n");
}
Status LT(KeyType a, KeyType b)
{
if(a<b)
return TRUE;
else
return FALSE;
}
void bubble_sort(SqList *L)
{
int i, j;
_Bool change;
RedType tmp;
for(i=L->length, change=TRUE; i>=2 && change; i--)
{
change = FALSE;
for(j=1; j<i; j++)
if(LT(L->r[j+1].key, L->r[j].key))
{
tmp = L->r[j];
L->r[j] = L->r[j+1];
L->r[j+1] = tmp;
change = TRUE;
}
}
}
void main()
{
SqList L;
ListInsert(&L);
bubble_sort(&L);
ListTraverse(L);
}