数据结构 笔记:冒泡排序和希尔排序

冒泡排序的基本思想

-每次从后向前进行(假设为第i次),j = n -1 ,n- 2,...,i,两辆比较 V[j-1]和V[j]的关键字;如果发生逆序,则交换V[j-1]和V[j].

template <typename T>
    static void Bubble(T array[], int len, bool min2max = true)
    {
        bool exchange = true;

        for(int i = 0;(i <len) && exchange;i++)
        {
            exchange = false;

            for(int j = len-1;j > i;j--)
            {
                if(min2max? (array[j] < array[j-1]) :(array[j] > array[j-1]) )
                {
                    Swap(array[j],array[j-1]);
                    exchange = true;
                }
            }
        }
    }

希尔排序的基本思想

-将待排序列划分为若干组,在每一组内进行插入排序,以使整个序列基本有序,然后在对整个序列进行插入排序

template < typename T>
    static void Shell(T array[] , int len, bool min2max = true)
    {
        int d = len;

        do
        {
            d = d / 3 + 1;
            for(int i = d;i<len;i++)
            {
                int k = i;
                T e = array[i];

                for(int j=i-d;(j>=0) && (min2max? (array[j]>e) :(array[j] <e));j-=d)
                {
                    array[j+d] = array[j];
                    k = j;
                }

                if(k != i)
                {
                    array[k] = e;
                }
            }
        }while( d > 1);
    }

总结:

-冒泡排序每次从后向前将较小的元素交互到位

-冒泡排序是一种稳定的排序法,其复杂度为O(n^2)

-希尔排序通过分组的方式进行多次插入排序

-希尔排序是一种不稳定的排序法,其复杂度为O(n^ 3/2)

猜你喜欢

转载自blog.csdn.net/qq_29962483/article/details/83893753