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