数据结构思维笔记(二) 算法分析

1.简单算法分类
  • 常数时间O(1):不依赖于输入
  • 线性O(n):依赖于输入,并跟输入量大小成正比
  • 平方O(n^2 ):随着n的增长变为n^2
2.简单排序
public class SelectionSort {

    /**
     * Swaps the elements at indexes i and j.
     */
    public static void swapElements(int[] array, int i, int j) {
        int temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }

    /**
     * Finds the index of the lowest value
     * starting from the index at start (inclusive)
     * and going to the end of the array.
     */
    public static int indexLowest(int[] array, int start) {
        int lowIndex = start;
        for (int i = start; i < array.length; i++) {
            if (array[i] < array[lowIndex]) {
                lowIndex = i;
            }
        }
        return lowIndex;
    }

    /**
     * Sorts the elements (in place) using selection sort.
     */
    public static void selectionSort(int[] array) {
        for (int i = 0; i < array.length; i++) {
            int j = indexLowest(array, i);
            swapElements(array, i, j);
        }
    }
}

swap()是常数级操作,时间恒定
indexLowest()复杂度,同n-start有关,属于线性关系
selectionSort(),需要算n(n-1)/2,属于平方关系


原书链接:https://wizardforcel.gitbooks.io/think-dast/content/1.html
GitHub链接(提供源码):https://github.com/huoji555/Shadow/tree/master/DataStructure

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值