[问题] C语言 Bubble Sort with linked-list

楼主: airwaves (airwaves)   2019-10-08 11:19:15
各位大神好,
最近在学习C语言。
想要用linked-list写bubble sort
这是我参考网络上的做法,最后有成功排序的程式码
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
};
void printLinkedList(struct node *start);
void swap(struct node *node1, struct node *node2);
void bubbleSort(struct node *start);
// ================================================
int main()
{
int arry[10];
struct node *prev, *first = NULL, *current;
printf("Please type in the 01st number:");
scanf("%d", &arry[0]);
printf("Please type in the 02nd number:");
scanf("%d", &arry[1]);
printf("Please type in the 03rd number:");
scanf("%d", &arry[2]);
printf("Please type in the 04th number:");
scanf("%d", &arry[3]);
printf("Please type in the 05th number:");
scanf("%d", &arry[4]);
printf("Please type in the 06th number:");
scanf("%d", &arry[5]);
printf("Please type in the 07th number:");
scanf("%d", &arry[6]);
printf("Please type in the 08th number:");
scanf("%d", &arry[7]);
printf("Please type in the 09th number:");
scanf("%d", &arry[8]);
printf("Please type in the 10th number:");
scanf("%d", &arry[9]);
int i;
for (i = 0; i < 10; i++)
{
current = (struct node*)malloc(sizeof(struct node));
current -> data = arry[i];
if (i == 0)
{
first = current;
}
else
{
prev -> next = current;
}
current -> next = NULL;
prev = current;
}
printf("\n");
printf("List before sorting:");
printLinkedList(first);
printf("\n");
bubbleSort(first);
printf("List after sorting:");
printLinkedList(first);
printf("\n\n");
return 0;
}
// ================================================
void printLinkedList(struct node *start)
{
struct node *tmp = start;
while(tmp != NULL)
{
printf("%d,", tmp -> data);
tmp = tmp -> next;
}
}
//
作者: Gway (我爱的你 也爱我 好吗?)   2019-10-08 17:04:00
你写的的终止条件有可能不会满足而造成无穷循环欧
作者: jepk007 (NW-吉普)   2019-10-08 17:42:00
不觉得第一段输入的部分重复性很高吗
作者: Gway (我爱的你 也爱我 好吗?)   2019-10-08 18:43:00
我眼残 把startSort = startSort -> next;看成在括号内 请忽略我讲的 囧 但你的终止条件确实定的比较不好 用flag主要是看还有没有bubble(I.eswap的动作)你的写法是无条件都做
作者: alan23273850   2019-10-09 12:00:00
我没仔细检查,但印象中起标只是侦测已排序后提早终止,是加速的手段,跟正确性无关
作者: fragmentwing (片翼碎梦)   2019-10-15 15:23:00
你如果担心有多做 首先改成随机输入1~10(反正就是1~10随机交换几百次后丢进去排序)立参数a1 a2纪录该次排序次数 b1 b2纪录总排序次数每次大概做10次后看你高兴要不要继续就按个键啥的相信很快就能看出来了

Links booklink

Contact Us: admin [ a t ] ucptt.com