算法combSort()

作者: 街头的慢慢 | 来源:发表于2017-04-23 21:03 被阅读33次

    梳排序的基本思想:梳排序是在冒泡排序上再做优化的。梳排序是待排序列通过增量分为若干个子序列,然后对子序列进行冒泡排序,然后一步步减少增量,直到增量减到1为止。梳排序的最后一次排序是冒泡排序。
    梳排序的增量是根据递减率减小的,递减率的设定影响着梳排序的效率,最有效的递减率为1.3。


    j = n, s = 1.3, flag = false;
    while j > 0 or flag = true do
       i = 0; j = max{(j / s), 1}; flag = false;
       while i + j <= n do
          if a[i] > a[i + j] then
             交换a[i]和a[i + j];
             flag = true;
          end if
       end while
    end while
    

    c语言:

    #include <stdio.h>
    
    void combSort(int num[],int n)
    {
        int incre = n;
        int i;
        while(incre >= 1)
        {
            incre /= 1.3;
            i = 0;
            while(i + incre < n)
            {
                if(num[i] > num[i + incre])
                {
                    int t = num[i];
                    num[i] = num[i + incre];
                    num[i + incre] = t;
                }
                i++;
            }
        }
    }
    int main(void)
    {
        int n, i, j;
        scanf("%d",n);
        int num[5];
        for(i = 0;i < n;i++)
        {
            scanf("%d",num[i]);
        }
        combSort(num,n);
        for(i = 0;i < n;i++)
        {
            printf("%d ",num[i]);
        }
    }
    

    java:

    import java.util.Scanner;
    
    public class Main {
    
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            
            Scanner in = new Scanner(System.in);
            int n = in.nextInt();
            int []num = new int[n];
            for(int i = 0;i < n;i++)
            {
                num[i] = in.nextInt();
            }
            combSort(num,n);
            for(int i = 0;i < n;i++)
            {
                System.out.print(num[i] + " ");
            }
    
        }
        public static void combSort(int []num,int n)
        {
            int incre = n;
            while(incre >= 1)
            {
                int i = 0;
                incre /= 1.3;
                while(i + incre < n)
                {
                    if(num[i] > num[i + incre])
                    {
                        int t = num[i];
                        num[i] = num[i + incre];
                        num[i + incre] = t;
                    }
                    i++;
                }
            }
        }
    
    }
    
    

    相关文章

      网友评论

        本文标题:算法combSort()

        本文链接:https://www.haomeiwen.com/subject/zigyzttx.html