Realization of common sort algorithm (ii.)-shell sorting

Source: Internet
Author: User

The shell sort is a modification to the insertion sort, it divides the elements of the sequence into several subsequence by an increment each time, inserts a sequence of these substrings, and then increments the number of elements in each subsequence until the increment is one, and the subsequence is the same as the previous sequence, At this point, only a small amount of comparison and movement can be done to sort the sequence.

// shell排序
void ShellSort(int array[], int length)
{
    int temp;

    // 增量从数组长度的一半开始,每次减小一倍
    for (int increment = length / 2; increment > 0; increment /= 2)
        for (int i = increment; i < length; ++i)
        {
            temp = array[i];
            // 对一组增量为increment的元素进行插入排序
            for (int j = i; j >= increment; j -= increment)
            {
                // 把i之前大于array[i]的数据向后移动
                if (temp < array[j - increment])
                {
                    array[j] = array[j - increment];
                }
                else
                {
                    break;
                }
            }
            // 在合适位置安放当前元素
            array[j] = temp;
        }
}

Animation Demo:

Http://202.113.89.254/DataStructure/DS/web/flashhtml/shell.htm

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.