Hill sort and quick sort and reverse singly linked list

The idea of ​​quick sort is to choose a number. The smaller number than me is ranked in front of me. The larger number is ranked behind me. Finally, the left and right sub-intervals are recursed.

int quicksort(int *data, int left, int right) { //Each recursion, each call, determine the correct position of a value

if (left >= right) return 0;

    int i = left;
    int j = right;
    int key = data[left];

while (i < j) { //

        while (i < j && key < data[j]) { // 
            j --;
        }
        data[i] = data[j];

        while (i < j && key >= data[i]) {
            i ++;
        }
        data[j] = data[i];
    }
    // i == j
    data[i] = key;

    //Recurse the left and right sub-intervals
    quicksort(data, left, i-1);
    quicksort(data, i+1, right );

}

Hill sort 

int shell_sort(int *data, int length) {
    int gap = 0; //分组的跨度
    int i = 0, j = 0;

    for (gap = length / 2; gap >= 1;gap /= 2) { // Number of groupings

        for(i = gap; i < length; i ++) { // Traverse each group 

            int temp = data[i];
            for (j = i - gap; j >= 0 && temp < data[j];j = j - gap) { //Inner exclusion order

                data[j+gap] = data[j];

            }

            data[j+gap] = temp;
        }

    }
    return 0;
}

The biggest problem with reversing a singly linked list is that you can't find your back-drive node after reversing it, so just save your back-drive node first.

struct list_node {
    int value;
    struct list_node *next;
};

struct list_node* reverse_list(struct list_node *head) {
    struct list_node *prev = NULL;
    struct list_node *current = head;

    while (current) {
        
        struct list_node *node = current ->next;
        current->next = prev;
        prev = current;
        current = node;

    }

    return prev;
}
————————————————
Copyright statement: This article is an original article by CSDN blogger "Killing God Li" and follows the CC 4.0 BY-SA copyright agreement. Please attach the original source link and this statement when reprinting.
Original link: https://blog.csdn.net/qq_16401691/article/details/125041541

Guess you like

Origin blog.csdn.net/qq_51710331/article/details/125063902