常用排序算法—Shell Sort(希尔排序)

Shell sort works by comparing elements that are distant rather than adjacent elements in an array or list where adjacent elements are compared. Shellsort uses an increment sequence. The increment size is reduced after each pass until the increment size is 1. With an increment size of 1, the sort is a basic insertion sort, but by this time the data is guaranteed to be almost sorted, which is insertion sort's "best case". The distance between comparisons decreases as the sorting algorithm runs until the last phase in which adjacent elements are compared hence, it is also known as diminishing increment sort.

Algorithm:

1. n = length of the list, increment = n/2

2. Do the following until increment>0

              i = increment until i<n do the following

             Store the value at index i in a temporary variable(temp)

             j = i until j>= increment do the following

                    • If temp is less than the value at index j-increment

                    Replace the value at index j with the value at index j-increment and

                    decrease j by increment.

                    • Else break out of the j loop.

              Replace the value at index j with temp and increase i by 1.

Divide increment by 2.

 

void ShellSort(int *array, int number_of_elements)
{
    int iter, jter, increment, temp;        
    for(increment = number_of_elements/2;increment > 0; increment /= 2)      
    {
        for(iter= increment; iter<number_of_elements; iter++)                
        {                        
            temp = array[iter];         
            for(jter = iter; jter >= increment ;jter-=increment)     
            {
                if(temp < array[jter-increment])     
                {
                    array[jter] = array[jter-increment];        
                }                               
                else                                
                {
                    break;                                
                }                        
            }
            array[jter] = temp;                
        }   
    }
}

 

 

Property:

1. Best-Case Complexity- O(n) when array is already sorted.

2. Worst-Case Complexity-It depends on gap sequence; best known is O( n (log n)2 ) and

occurs when array is sorted in reverse order.

3. Average-Case Complexity- It also depends on gap sequence.

4. O(1) extra space and it is not stable.

5. It’s only efficient for medium size lists. it is a complex algorithm and it’s not nearly as

efficient as the merge, heap, and quick sorts.

转载于:https://www.cnblogs.com/gigbit/archive/2013/03/21/2974439.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值