排序算法

对一个固定长度的数组或者一块连续空间存储的乱序的结构进行排序。

1、直接插入排序

typedef struct{
    int key;
    float info;
}JD;

void straightsort(JD r [], int n)
{
    int i,j;
    for (i = 2; i <= n ; i++)
    {
        r[0] = r[i];
        j = i-1;
        while(r[0].key < r[j].key)
        {
            r[j+1] = r[j];
            j--;
         }
         r[j+1] = r[0];
    }
}

相对应的链表排序的方法如下:

struct ListNode* sortList(struct ListNode* head){
    if (head == NULL || head->next == NULL)
        return head;
    
    struct ListNode *sort_pre = head;
    struct ListNode *cur = head->next;
    struct ListNode *cur_pre = head;
    struct ListNode *tmp = cur;
    struct ListNode *sort = head;
    
    while(cur) {
        tmp = cur->next;
        while (sort != cur && sort->val < cur->val) {
            sort_pre = sort;
            sort = sort->next;
        }
        
        if (sort == cur) {
            cur_pre = cur;
            goto finish;
        }
        
        if (sort == head) {           
            cur_pre->next = cur->next;
            cur->next = sort;
            head = cur;
            goto finish;
        }
        
        if (sort != cur) {
            cur_pre->next = cur->next;
            sort_pre->next = cur;
            cur->next = sort;
        }
         
finish:
        cur = tmp;
        sort = head;
        sort_pre = head;
    }
    
    return head;
}

为了验证链表插入排序的算法,还写了数组构造成链表的方法,代码如下:

struct ListNode{
    int val;
    struct ListNode *next;
};

struct ListNode * create_list(int *array, int n) {
    int i;
    struct ListNode *head = malloc(sizeof(struct ListNode));
    struct ListNode *node;
    struct ListNode *cur = head;
    head->val = array[0];
    head->next = NULL;

    for(i = 1; i < n; i++)
    {
        node = malloc(sizeof(struct ListNode));
        node->val = array[i];
        node->next = NULL;
        cur->next = node;
        cur = node;
    }

    return head;
}

void print_list(struct ListNode * head)
{
    struct ListNode *cur = head;
    while(cur)
    {
        printf("%d
", cur->val);
        cur = cur->next;
    }
}
原文地址:https://www.cnblogs.com/xingmuxin/p/11315233.html