Sorting algorithm--shell sorting

Source: Internet
Author: User

Principle

Divides the sorted array into sub-sequences (this depends on the originally set step value), then inserts the sequence directly between the individual sub-sequences, and then the increment (that is, the step value) and then inserts the sort, until the sequence is basically stable (the step size is small enough), a direct insert sort of the series, When sorting is good, the efficiency of direct insertion is quite high.

Analysis

In the worst case, each number will always be compared in the process of each comparison, so in the worst case its time complexity O(n2). In the best case, the sequence is basically ordered only once, so the time complexity is O(n). The space complexity is O(1).

C Language Implementation

Void swap (void *a, void *b, int size) {    void *tmp  = malloc (size);     memcpy (tmp, a, size);     memcpy (a, b, size);     memcpy (b, tmp, size);     Free (TMP);} Void shell_sort (Int *arr, int arrlen) {    int i = 0,  j = 0;    int gap = 0;    if (NULL  == arr | |  0 >= arrlen) {        return ;     }    for (gap = arrlen/2; gap>0; gap /= 2) {         for (I = gap; i < arrlen; ++i) {            for (j = i - gap;& nbSP;J&NBSP;&GT;=0;&NBSP;J&NBSP;-=&NBSP;GAP) {                 if (Arr[j] > arr[j + gap]) {                     swap (&arr[j],  &arr[j + gap], sizeof (Arr[j]);                 }             }        }    }}


This article is from the "11219885" blog, please be sure to keep this source http://11229885.blog.51cto.com/11219885/1751536

Sorting algorithm--shell sorting

Related Article

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.