• Hark的数据结构与算法练习之梳排序


    算法说明
    梳排序是交换排序的一种,它其实也是改自冒泡排序,不同之处是冒泡排序的比较步长恒定为1,而梳排序的比较步长是变化的。

    步长需要循环以数组长度除以1.3,到最后大于等于1即可。

    光说可能比较抽象,所以实例举个例子可能会好些,这里使用的例子从这里转载过来的

    假设待数组[8 4 3 7 6 5 2 1]

    待排数组长度为8,而8÷1.3=6,则比较8和2,4和1,并做交换

    [8 4 3 7 6 5 2 1]

    [8 4 3 7 6 5 2 1]

    交换后的结果为

    [2 1 3 7 6 5 8 4]

    第二次循环,更新间距为6÷1.3=4,比较2和6,1和5,3和8,7和4

    [2 1 3 7 6 5 8 4]

    [2 1 3 7 6 5 8 4]

    [2 1 3 7 6 5 8 4]

    [2 1 3 7 6 5 8 4]

    只有7和4需要交换,交换后的结果为

    [2 1 3 4 6 5 8 7]

    第三次循环,更新距离为3,没有交换

    第四次循环,更新距离为2,没有交换

    第五次循环,更新距离为1,三处交换

    [2 1 3 4 6 5 8 7]

    [2 1 3 4 6 5 8 7]

    [2 1 3 4 6 5 8 7]

    三处交换后的结果为[1 2 3 4 5 6 7 8]

    交换后排序结束,顺序输出即可得到[1 2 3 4 5 6 7 8]

    代码

    使用的是java

    package hark.sort.exchangesort;
    
    /*
     * 梳排序
     */
    public class CombSort {
    	public static void main(String[] args) {
    		int[] arrayData = { 5, 3, 2, 4, 3, 1, 2, 1, 4, 2, 4, 21, 6, 3, 2, 1 };
    		CombSortMethod(arrayData);
    		for (int integer : arrayData) {
    			System.out.print(integer);
    			System.out.print(" ");
    		}
    	}
    
    	public static void CombSortMethod(int[] arrayData) {
    		float shrink_factor = 1.3f;
    		int length = arrayData.length;
    		int temp;
    		int stepSize = (int) (arrayData.length / shrink_factor);  //步长变化,除以1.3
    		while (stepSize >= 1) {  //步长大于等于1
    			for (int i = 0; i < length; i++) {
    				if (i + stepSize >= length) { // 如果超出数组长度,就break跳出
    					break;
    				}
    				
    				if (arrayData[i] < arrayData[i + stepSize]) {
    					temp = arrayData[i];
    					arrayData[i] = arrayData[i + stepSize];
    					arrayData[i + stepSize] = temp;
    				}
    			}
    			stepSize = (int) (stepSize / shrink_factor);  //步长变化,除以1.3
    		}
    
    	}
    }
    

    时间复杂度:

    O(nlog2n)

    空间复杂度:

    O(1)

    稳定性:

    非稳定

    参考

    http://zh.wikipedia.org/wiki/%E6%A2%B3%E6%8E%92%E5%BA%8F

    http://www.cnblogs.com/kkun/archive/2011/11/23/2260293.html

  • 相关阅读:
    php 调试
    php 格式
    php 函数 将数组转换成标量变量:extract()
    jQuery 方法
    php echo字符串的连接格式
    wampserver php 设置时间
    TableView使用CATransform3D特效动画
    苹果手机制作gif图片
    全局修改Lable/Button字体
    关于 presentViewController 时机
  • 原文地址:https://www.cnblogs.com/hark0623/p/4360560.html
Copyright © 2020-2023  润新知