[問題] 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