Bootstrap

数据结构第八章交换排序-冒泡排序(C语言代码)

#define MAX_SIZE 20
typedef struct
{
	int key;
}ElemType;
typedef struct
{
	ElemType* R;
	int length;
}Sqlist;

void Create(Sqlist* L)
{
	int i, n;
	printf("请输入数据个数,不能超过%d\n", MAX_SIZE);
	scanf("%d", &n);
	while (n>MAX_SIZE)
	{
		printf("数据个数超过总数,请重新输入\n");
		scanf("%d", &n);
	}
	L->R = (ElemType*)malloc(sizeof(ElemType) * (MAX_SIZE + 1));
	L->length = 0;
	printf("请输入元素内容:\n");
	for (i = 0; i < n; i++)
	{
		scanf("%d", &L->R[i].key);
		L->length++;
	}
}
void BubbleSort(Sqlist* L)
{
	int i, j;
	for (i = 0; i < L->length - 1; i++)
	{
		for (j = 0; j < L->length - 1 - i; j++)
		{
			if (L->R[j].key > L->R[j + 1].key)
			{
				ElemType temp = L->R[j + 1];
				L->R[j + 1] = L->R[j];
				L->R[j] = temp;
			}
		}
	}
}
void printNode(Sqlist L)
{
	for (int i = 0; i < L.length; i++)
	{
		printf("%d ", L.R[i].key);
	}
}
int main()
{
	Sqlist L;
	Create(&L);
	BubbleSort(&L);
	printNode(L);
	return 0;
}

4162e40239a04a3ebb56bf1243e0ed34.png

链式存储结构如下:

typedef struct Node
{
	int data;
	struct Node* next;
}Node;
Node* Create(int data)
{
	Node* newnode = (Node*)malloc(sizeof(Node));
	if (newnode == NULL)
	{
		perror("error:");
		exit(1);
	}
	newnode->data = data;
	newnode->next = NULL;
}
Node* CreateArr(int arr[], int size)
{
	Node* newnode = Create(arr[0]);
	Node* temp = newnode;

	for (int i = 1; i < size; i++)
	{
		temp->next = Create(arr[i]);
		temp = temp->next;
	}
	return newnode;
}
void printNode(Node* node)
{
	Node* temp = node;
	while (temp)
	{
		printf("%d->", temp->data);
		temp = temp->next;
	}
	printf("NULL\n");
}
void FreeNode(Node* node)
{
	Node* temp = node;
	while (temp)
	{
		Node* pcur = temp->next;
		free(temp);
		temp = pcur;
	}
}
void BubbleSort(Node** headRef)
{
	Node* head = *headRef;
	Node* end = NULL;
	while (head->next != end)
	{
		Node* temp = head;
		while (temp->next!=end)
		{
			Node* pcur = temp->next;
			if (temp->data >pcur->data)
			{
				int node = pcur->data;
				pcur->data = temp->data;
				temp->data = node;
			}
			temp = temp->next;
		}
		end = temp;//9 8 .....
	}
}
int main()
{
	int arr[] = { 4,3,5,1,9,6 };
	int size = sizeof(arr) / sizeof(arr[0]);
	Node* node = CreateArr(arr, size);
	printf("初始遍历:\n");
	printNode(node);
	BubbleSort(&node);
	printf("排序后的遍历:\n");
	printNode(node);
	FreeNode(node);
	return 0;
}

;