前言
正在读《数据结构与算法图解》一书,被其简单明了的讲解折服,其中涉及到了很多有用的算法,为了加深印象以及理解,便跟着把其中的代码转换为我平时所使用的的语言java。
每种算法的时间复杂度标识出来。
第 1 章 数据结构为何重要
第 2 章 算法为何重要
1、二分查找
- 时间复杂度
- 基于有序数组
/**
* @author xch
* @params [arrays, value]
* @return java.lang.Integer
* @description 二分查找
*/
public static Integer binarySearch(int [] arrays, int value) {
int lowerBound = 0;
int upperBound = arrays.length - 1;
while (lowerBound <= upperBound) {
int midPoint = (upperBound + lowerBound) / 2;
int valueAtMidpoint = arrays[midPoint];
if (value < valueAtMidpoint) {
upperBound = midPoint - 1;
} else if (value > valueAtMidpoint) {
lowerBound = midPoint + 1;
} else {
return midPoint;
}
}
return null;
}
第 3 章 大O记法
第 4 章 运用大O来给代码提速
1、冒泡排序
- 时间复杂度
/**
* @author xch
* @params [arrays]
* @return int[]
* @description 冒泡排序
*/
public static int [] bubbleSort(int [] arrays) {
int unsortedUntilIndex = arrays.length - 1;
boolean sorted = false;
while (!sorted) {
sorted = true;
for (int i = 0; i< unsortedUntilIndex; i++) {
if (arrays[i] > arrays[i + 1]) {
sorted = false;
int temp = arrays[i];
arrays[i] = arrays[i + 1];
arrays[i + 1] = temp;
}
}
unsortedUntilIndex = unsortedUntilIndex - 1;
}
return arrays;
}
第 5 章 用或不用大O来优化代码
1、选择排序
- 时间复杂度
/**
* @author xch
* @params [arrays]
* @return int[]
* @description 选择排序
*/
public static int[] selectSort(int [] arrays) {
for(int i = 0; i < arrays.length; i++) {
int lowestNumberIndex = i;
for (int j = i + 1; j < arrays.length; j++) {
if (arrays[j] < arrays[lowestNumberIndex]) {
lowestNumberIndex = j;
}
}
if (lowestNumberIndex != i) {
int temp = arrays[i];
arrays[i] = arrays[lowestNumberIndex];
arrays[lowestNumberIndex] = temp;
}
}
return arrays;
}
第 6 章 乐观地调优
1、插入排序
- 时间复杂度
/**
* @author xch
* @params [arrays]
* @return int[]
* @description 插入排序
*/
public static int[] insertSort(int [] arrays) {
for (int i = 1; i < arrays.length; i++) {
int position = i;
int temp = arrays[i];
while (position > 0 && arrays[position - 1] > temp) {
arrays[position] = arrays[position - 1];
position = position - 1;
}
arrays[position] = temp;
}
return arrays;
}