zoukankan      html  css  js  c++  java
  • Stooge 排序

    Stooge排序是一种低效的递归排序算法,甚至慢于冒泡排序。在《算法导论》第二版第7章(快速排序)的思考题中被提到,是由HowardFine等教授提出的所谓“漂亮的”排序算法。

    实现

    • 如果最后一个值小于第一个值,则交换它们
    • 如果当前子集元素数量大于等于3:
    1. 使用Stooge排序前2/3的元素
    2. 使用Stooge排序后2/3的元素
    3. 再次使用Stooge排序前2/3的元素
    #include<stdio.h>    
    #include<string.h>   
    #include<math.h>   
    #include<ctype.h>   
    #include<stdbool.h>  
    
    void swap(int *a, int *b)   //交换两元素的值
    {
        int t;
        t=*a;
        *a=*b;
        *b=t;
    }
    
    void printArray(int a[], int count)   //打印数组元素
    {
        int i;
        for(i=0; i<count; i++)
            printf("%d ",a[i]);
        printf("\n");
    }
    
    void stooge_sort(int a[], int left, int right)
    {
    
        int t;
        if(a[left]>a[right])
            swap(&a[left], &a[right]);
        if(right-left+1 >= 3)
        {
            t=(right-left+1)/3;
            stooge_sort(a,left,right-t);
            stooge_sort(a,left+t,right);
            stooge_sort(a,left,right-t);
        }
     
    }
    
    int main(void)   
    {
        int a[]={3, 5, 4, 6, 9, 7, 8, 0, 1};
        int n=sizeof(a)/sizeof(*a);
        printArray(a,n);
        stooge_sort(a,0,n-1);
        printArray(a,n);
        return 0;
    }

    算法的复杂度正比于: T(n)=3T(2n/3)+1. 已被证明时间复杂度接近于O(n2.71) ,可见此算法效率相当的低下,比选择、插入、冒泡排序更差

  • 相关阅读:
    为什么不应该使用ZooKeeper做服务发现
    Python 练习 人事管理
    Python 爬取 妹子图(技术是无罪的)
    Python 爬取 书籍
    Python 爬取 豆瓣
    Python 爬取 房天下
    Python 爬取 煎蛋
    Python 爬取 拉钩
    Python 爬取 猫眼
    家具专区网
  • 原文地址:https://www.cnblogs.com/cpoint/p/3367362.html
Copyright © 2011-2022 走看看