Sort

void Sort1(Node **head)
{
    if (head == NULL)
        return;
 
    int i, j, n, temp, swap_time;
    Node *p1, *p2;
    n = Length1(*head);                // Bubble Sort: need to know length
 
    for (i = 1; i <= n - 1 && swap_time; i++) {              // if swap_time == 0, break and return
        p1 = *head;                          // start to swap from the beginning of the linked list
        p2 = (*head)->next;
 
        for (j = 1, swap_time = 0; j <= n - i; j++) {
            if (p1->data > p2->data) {                  // if p1 > p2 then swap, if p1 = p2 don't swap -> stable
                temp = p2->data;
                p2->data = p1->data;
                p1->data = temp;
                swap_time++;             // count swap time
            }
            p1 = p1->next;
            p2 = p2->next;
        }
    }
}
 
Node* Sort2(Node *head)
{
    Node *p1 = head;
    int cnt = 0, i, j, tmp, swap_time;
    while (p1 != NULL) {
        cnt++;
        p1 = p1->next;
    }
    for (i = 1; i < cnt; i++) {
        p1 = head;
        swap_time = 0;
        for (j = 0; j < cnt - i; j++) {
            if (p1->data > p1->next->data) {
                tmp = p1->data;
                p1->data = p1->next->data;
                p1->next->data = tmp;
                swap_time++;
            }
            p1 = p1->next;
        }
        if (!swap_time)
            break;
    }
    return head;
}
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License