The implementation of Hill sorting algorithm

Source: Internet
Author: User

Hill Sort (shellsort) is also called incremental decrement (diminishing increment) sorted by D.L. Shell invented, this algorithm is through a gradual decrease in the increment of an array gradually to the order to achieve the purpose of sorting.

Suppose there is an array int data[16] = {...}. The first increment is set to 16/2 = 8, which divides the array into 8 sub arrays, with indices of 0, 8 1, 9 2, 10, and so on. Sorts the child arrays. Then the increment is 8/2 = 4, so that the original array is divided into 4 sub arrays, and their indexes are 0, 4, 8, 12 1, 5, 9, 13, and so on. The four sets of numbers are then sorted until the increment is 1.

The incremental decrement described above is only one method, and this method is not the most efficient. such as f (n) = 3 * F (n-1) + 1 f (1) = 1 (..., 121, 40, 13, 4, 1) is better than the increment method above. The time complexity of this method is O (n ^1.5).

Algorithm is as follows

#include <stdio.h>
    
void output_array (int data[], int n)
{
    int i;
    for (i = 0; i < n; i++)
        printf ("%d", Data[i]);
    printf ("\ n");
}
void swap (int *a, int *b)
{
    int x;
    x = *a;
    *a = *b;
    *b = x;
}
void Insertion_sort (int data[], int n, int increment)
{
    int i, J;
    for (i = increment i < n; i + = increment) for
        (j = i; j >= increment && data[j] > Data[j-increment] ; J-= increment)
            swap (&data[j], &data[j-increment])
;
void Shellsort (int data[], int n)
{
    int i, J;
    for (i = N/2 i > 2; I/= 2) for
        (j = 0; J < i; j +)
            Insertion_sort (data + j, n-j, I);
    Insertion_sort (data, n, 1);
}
int main ()
{
    int data[] = {5, 3, 1, 665, 9, 8, 6};
    Output_array (data,);
    Shellsort (data,);
    Output_array (data,);
    return 0;
}

This article is from "Li Ning's Geek World" blog, please be sure to keep this source http://androidguy.blog.51cto.com/974126/215348

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.