GreensnoWorld
记录点滴,分享乐趣,一块凝固的时间
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);
}
LIJG
余本顽劣,生于紫云下,长于汝水滨。早年求学,兴趣广泛,好高骛远,学无所成,仓皇入世。兴趣所致,投身互联网,求知未证,而立已至,始悟光阴荏苒,终需务实钻研。故有此站,记录时光,积累点滴,验证所学,分享愚见。指舞方寸间,心系万千年。
留言