时间复杂度
1.常数时间的操作:一个操作如果和数据量没有关系,每次都是固定时间内完成的操作,叫做常数操作。 例如:数组寻址、加减乘除都是常数操作。
2.时间复杂度为一个算法流程中,常数操作数量的指标,常用O(读作big O)来表示,如O(N)。在常数操作数量的表达式中, 只要高阶项,不要低阶项,也不要高阶项的系数,剩下的部分如果记为f(N),那么时间复杂度为O(f(N))。
例:一个有序数组A,另
一个无序数组B,请打印B中的所有不在A中的数,A数组长度为N,B数组长度为M。
算法1:对于数组B中的每一个数,都在A中通过遍历的方式找一下;
算法2:对于数组B中的每一个数,都在A中通过二分的方式找一下;
算法3:先把数组B排序,然后用类似外排的方式打印所有在A中出现的数;
算法1的时间复杂度:O(MxN);
算法2的时间复杂度:O(Mxlog2N)(8个元素的数组利用二分法只需要找三次)
算法3的时间复杂度:O(Mxlog2M)+O(M+N)(前者为数组排序的时间复杂度,后者为外排的时间复杂度)
算法2跟算法3的好坏取决于M、N的大小
3.递归行为的时间复杂度:master公式的使用
T(N) = a*T(N/b) + O(N^d)
- log(b,a) > d -> 复杂度为O(N^log(b,a))
- log(b,a) = d -> 复杂度为O(N^d * logN)(log默认以2为底)
- log(b,a) < d -> 复杂度为O(N^d)
排序算法
- 冒泡排序
1.比较相邻的元素。如果第一个比第二个大,就交换他们两个。
2.对每一对相邻元素做同样的工作,从开始第一对到结尾的最后一对。在这一点,最后的元素应该会是最大的数。(每次排好末尾一个数)
3.针对所有的元素重复以上的步骤,除了最后一个。
4.持续每次对越来越少的元素重复上面的步骤,直到没有任何一对数字需要比较。
public static void bubbleSort(int[] arr) {
if (arr == null || arr.length < 2) {
return;
}
for (int e = arr.length - 1; e > 0; e--) {
for (int i = 0; i < e; i++) {
if (arr[i] > arr[i + 1]) {
swap(arr, i, i + 1);
}
}
}
}
//交换两个数组元素的值,也可以利用中间变量temp交换
public static void swap(int[] arr, int i, int j) {
arr[i] = arr[i] ^ arr[j];
arr[j] = arr[i] ^ arr[j];
arr[i] = arr[i] ^ arr[j];
}
冒泡排序的时间复杂度O(N^2),额外空间复杂度O(1),冒泡排序是稳定的。
- 选择排序
选择排序法是在要排序的一组数中,选出最小(或最大)的一个数与第一个位置的数交换;在剩下的数当中找最小的与第二个位置的数交换,即顺序放在已排好序的数列的最后,如此循环,直到全部数据元素排完为止。
public class test {
public static void selectionSort(int[] arr) {
if (arr == null || arr.length < 2) {
return;
}
for (int i = 0; i < arr.length - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < arr.length; j++) {
minIndex = arr[j] < arr[minIndex] ? j : minIndex;
}
swap(arr, i, minIndex);
}
}
public static void swap(int[] arr, int i, int j) {
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
public static void printArray(int[] arr) {
if (arr == null) {
return;
}
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
//test
public static void main(String[] args) {
int[] res = new int[5];
res= new int[]{3, 6, 8, 9, 0};
printArray(res);
selectionSort(res);
printArray(res);
}
}
选择排序的时间复杂度O(N^2),额外空间复杂度O(1),选择排序不具有稳定性。
- 插入排序
插入排序的基本思想是将一个记录插入到已经排好序的有序表中,从而一个新的、记录数增1的有序表。在其实现过程使用双层循环,外层循环对除了第一个元素之外的所有元素,内层循环对当前元素前面有序表进行待插入位置查找,并进行移动
public static void insertionSort(int[] arr) {
if (arr == null || arr.length < 2) {
return;
}
for (int i = 1; i < arr.length; i++) {
for (int j = i - 1; j >= 0 && arr[j] > arr[j + 1]; j--) {
swap(arr, j, j + 1);
}
}
}
public static void swap(int[] arr, int i, int j) {
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
插入排序的时间复杂度O(N^2),额外空间复杂度O(1),插入排序具有稳定性。
- 希尔排序
先将待排序的数组元素分成多个子序列,使得每个子序列的元素个数相对较少,然后对各个子序列分别进行直接插入排序,待整个待排序序列“基本有序后”,最后再对所有元素进行一次直接插入排序。
步骤:
①选择一个步长序列t1,t2,···,tk,满足ti > tj(i<j),tk=1。
②按步长序列个数k,对待排序序列进行k趟排序。
③每趟排序,根据对应的步长ti,将待排序列分割成ti个子序列,分别对各个子序列进行直接插入排序。
public class ShellSort {
public static void main(String[] args) {
int a[] = {3,6,9,5,7,2,1,0,8,4};
shellSort(a);
for(int i = 0; i < a.length; i ++) {
System.out.print(a[i] + " ");
}
}
private static void shellSort(int[] a) {
int len = a.length;
int i, j, h, temp;
for(h = len / 2; h > 0; h = h / 2) {
for(i = h; i < len; i ++) {
temp = a[i];
for(j = i - h; j >= 0; j -= h) {
if(temp < a[j]) {
a[j + h] = a[j];
}else
break;
}
a[j + h] = temp;
}
}
}
}
https://www.cnblogs.com/chengxiao/p/6104371.html
- 归并排序
该算法采用分治法(Divide and Conquer),将已有序的子序列合并,得到完全有序的序列;即先使每个子序列有序,再使子序列段间有序。若将两个有序表合并成一个有序表,称为二路归并。
public static void mergeSort(int[] arr) {
if (arr == null || arr.length < 2) {
return;
}
mergeSort(arr, 0, arr.length - 1);
}
public static void mergeSort(int[] arr, int l, int r) {
if (l == r) {
return;
}
//右移相当于除2,L和R中点位置(L+R)/2
int mid = l + ((r - l) >> 1);
//利用递归
mergeSort(arr, l, mid);
mergeSort(arr, mid + 1, r);
merge(arr, l, mid, r);
}
//合并
public static void merge(int[] arr, int l, int m, int r) {
//辅助数组
int[] help = new int[r - l + 1];
int i = 0;
int p1 = l;
int p2 = m + 1;
//合并操作
while (p1 <= m && p2 <= r) {
help[i++] = arr[p1] < arr[p2] ? arr[p1++] : arr[p2++];
}
//两个有且只有一个越界
//p1被剩下
while (p1 <= m) {
help[i++] = arr[p1++];
}
//p2被剩下
while (p2 <= r) {
help[i++] = arr[p2++];
}
for (i = 0; i < help.length; i++) {
arr[l + i] = help[i];
}
}
T(N) = 2*T(N/2) + O(N) a=2,b=2,d=1
归并排序的时间复杂度O(NxlogN),额外空间复杂度O(N),归并排序具有稳定性。
- 快速排序
通过一趟排序将要排序的数据分割成独立的两部分,其中一部分的所有数据都比另外一部分的所有数据都要小,然后再按此方法对这两部分数据分别进行快速排序,整个排序过程可以递归进行,以此达到整个数据变成有序序列。
public static void quickSort(int[] arr) {
if (arr == null || arr.length < 2) {
return;
}
quickSort(arr, 0, arr.length - 1);
}
public static void quickSort(int[] arr, int l, int r) {
if (l < r) {
//随机快速排序只需要加入下面一行代码,使得最后等于的值不是arr[r],而是任意一个arr[i]
//swap(arr,l+(int)(Math.random()*(r-l+1)),r)
int[] p = partition(arr, l, r);
quickSort(arr, l, p[0] - 1);
quickSort(arr, p[1] + 1, r);
}
}
//返回等于arr[r]的下标区间(经典的快排只有一个位置等于arr[r],一次递归只能有一个位置 排好,现在改进后可以有多个位置等于arr[r],一次递归有多个位置被排好)(荷兰国旗问题优化)
public static int[] partition(int[] arr, int l, int r) {
//小于arr[r]的下标右侧
int less = l - 1;
//大于arr[r]的下标左侧,arr[r]不参与排序
int more = r;
while (l < more) {
if (arr[l] < arr[r]) {
//调换位置后l位置++,因为++less位置的数确定比arr[r]的值小
swap(arr, ++less, l++);
} else if (arr[l] > arr[r]) {
//l位置不++,调换位置后继续循环,因为--more位置的数不能确定跟arr[r]的大小关系
swap(arr, --more, l);
} else {
l++;
}
}
//最终arr[r]位置与r位置交换,等于arr[r]的在一起
swap(arr, more, r);
return new int[] { less + 1, more };
}
public static void swap(int[] arr, int i, int j) {
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
快速排序的时间复杂度是O(nlogn),最坏的时间复杂度是n^2.快排不具有稳定性。
//快速排序的非递归实现
(1)对原数组进行一次划分,分别将左边的Record和右边的Record入栈stack。
(2)判断stack是否为空,若是,直接结束;若不是,将栈顶Record取出,进行一次划分。
(3)判断左边的Record长度大于1,将左边的Record入栈;同理,右边的Record。
(4)循环步骤2、3。
package sort.algorithm;
import java.util.Stack;
//快速排序的非递归实现,利用系统的栈stack
public class QuickSortNonRecursion {
public static void main(String[] args) {
QuickSortNonRecursion qsnr = new QuickSortNonRecursion();
int[] array = {0, 2, 11, 121, 18, 99, 3, 5, 101, 22, 9, 100};
qsnr.quicksort(array);
for (int i : array) {
System.out.print(i + " ");
}
}
public void quicksort(int[] array) {
if (array == null || array.length == 1) return;
//存放开始与结束索引
Stack<Integer> s = new Stack<Integer>();
//压栈
s.push(0);
s.push(array.length - 1);
//利用循环里实现
while (!s.empty()) {
int right = s.pop();
int left = s.pop();
//如果最大索引小于等于左边索引,说明结束了
if (right <= left) continue;
int i = partition(array, left, right);
if (left < i - 1) {
s.push(left);
s.push(i - 1);
}
if (i + 1 < right) {
s.push(i+1);
s.push(right);
}
}
}
//找到轴心,进行交换
public int partition (int[] data, int first, int end)
{
int temp;
int i=first,j=end;
if(first<end)
{
temp=data[i];
//当i=j的时候,则说明扫描完成了
while(i<j)
{
//从右边向左边扫描找到一个小于temp的元素
while(j>i&&data[j]>temp)j--;
if(i<j)
{
//将该元素赋值给temp
data[i]=data[j];
//赋值后就应该将i+1指向下一个序号
i++;
}
//然后从左边向右边开始扫描,找到一个大于temp的元素
while(i<j&&temp>data[i])i++;
if(i<j)
{
//将该元素赋值给temp
data[j]=data[i];
//赋值后就应该将j-1指向前一个序号
j--;
}
}
//将轴数据放在i位置中
data[i]=temp;
}
return i;
}
}
- 堆排序
堆是一个近似完全二叉树的结构,并同时满足堆积的性质:即子结点的键值或索引总是小于(小顶堆)或者大于(大顶堆)它的父节点。利用数组表示堆结构时,节点i的左子节点的位置为2xi+1、右子节点的位置为2xi+2、父节点的位置为(i-1)/2.
a.将无需序列构建成一个堆,根据升序降序需求选择大顶堆或小顶堆;
b.将堆顶元素与末尾元素交换,将最大元素"沉"到数组末端;
c.重新调整结构,使其满足堆定义,然后继续交换堆顶元素与当前末尾元素,反复执行调整+交换步骤,直到整个序列有序。(下沉重新找到堆顶)
public class test {
//堆排序
public static void heapSort(int[] arr) {
if (arr == null || arr.length < 2) {
return;
}
//成堆
for (int i = 0; i < arr.length; i++) {
heapInsert(arr, i); //0-i排好
}
//根与最后一个数交换
int size = arr.length;
swap(arr, 0, --size);
//下沉重新形成(大)顶堆,重复
while (size > 0) {
heapify(arr, 0, size);
swap(arr, 0, --size);
}
}
//形成大顶堆
public static void heapInsert(int[] arr, int index) {
while (arr[index] > arr[(index - 1) / 2]) {
swap(arr, index, (index - 1) / 2);
index = (index - 1) / 2;
}
}
//下沉重新形成大顶堆
public static void heapify(int[] arr, int index, int size) {
int left = index * 2 + 1;
while (left < size) {
//两个子节点比较大的一个上调
int largest = ((left + 1 < size) && (arr[left + 1] > arr[left])) ? left + 1 : left;
largest = arr[largest] > arr[index] ? largest : index;
if (largest == index) {
break;
}
swap(arr, largest, index);
index = largest;
left = index * 2 + 1;
}
}
public static void swap(int[] arr, int i, int j) {
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
}
堆排序的时间复杂度O(N*logN),额外空间复杂度O(1) 。如果只是建立堆的过程,时间复杂度为O(N) 。
- 桶排序
假定:输入是由一个随机过程产生的[0, 1)区间上均匀分布的实数。将区间[0, 1)划分为n个大小相等的子区间(桶),每桶大小1/n:[0, 1/n), [1/n, 2/n), [2/n, 3/n),…,[k/n, (k+1)/n ),…将n个输入元素分配到这些桶中,对桶中元素进行排序,然后依次连接桶输入0 ≤A[1…n] <1辅助数组B[0…n-1]是一指针数组,指向桶(链表)。桶排序是非基于比较的排序。
例:给定一个数组, 求如果排序之后, 相邻两数的最大差值, 要求时间复杂度O(N), 且要求不能用非基于比较的排序。
思路:利用桶排序,假设数组的长度为N,则准备N+1个空桶,最终一定有一个空桶,空桶是为了否定结果的相邻两数来自一个桶内部的可能性。
import java.util.Arrays;
public class MaxGap {
public static int maxGap(int[] nums) {
if (nums == null || nums.length < 2) {
return 0;
}
//遍历数组,找到数组中的最大值/最小值
int len = nums.length;
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
for (int i = 0; i < len; i++) {
min = Math.min(min, nums[i]);
max = Math.max(max, nums[i]);
}
//最大值和最小值相等时,所有值都一样,差值为0
if (min == max) {
return 0;
}
//表示每个桶中是否有值
boolean[] hasNum = new boolean[len + 1];
//表示每个桶中的最大值
int[] maxs = new int[len + 1];
//表示每个桶中的最小值
int[] mins = new int[len + 1];
int bid = 0;
for (int i = 0; i < len; i++) {
//确定数组中的值在哪个桶
bid = bucket(nums[i], len, min, max);
//调整相应桶中的最大值和最小值
mins[bid] = hasNum[bid] ? Math.min(mins[bid], nums[i]) : nums[i];
maxs[bid] = hasNum[bid] ? Math.max(maxs[bid], nums[i]) : nums[i];
//桶中有值标记为true
hasNum[bid] = true;
}
//寻找相邻差值最大值(后一个的最小值-前一个值最大值)
int res = 0;
int lastMax = maxs[0];
int i = 1;
for (; i <= len; i++) {
if (hasNum[i]) {
res = Math.max(res, mins[i] - lastMax);
lastMax = maxs[i];
}
}
return res;
}
//确定数组中的值在哪个桶
public static int bucket(long num, long len, long min, long max) {
return (int) ((num - min) * len / (max - min));
}
}
桶排序的时间复杂度是O(N).
稳定性
假定在待排序的记录序列中,存在多个具有相同的关键字的记录,若经过排序,这些记录的相对次序保持不变,即在原序列中,r[i]=r[j],且r[i]在r[j]之前,而在排序后的序列中,r[i]仍在r[j]之前,则称这种排序算法是稳定的;否则称为不稳定的
1.具有稳定性
- 冒泡排序
冒泡排序:遇到相等的值不交换直接跳入下一个 - 插入排序
插入排序:遇到相等的值不往左边继续比较 - 归并排序
归并排序:遇到相等的值先排左边
2.不具有稳定性
- 选择排序
选择排序:所有的数都跟第一个数交换,前面的可以换到后面。 - 快速排序
- 堆排序
对数器
对数器的的概念和使用步骤:
- 有一个你想要测的方法a;
- 实现一个绝对正确但是复杂度不好的方法b;
- 实现比对的方法;
- 把方法a和方法b比对很多次来验证方法a是否正确;
- 如果有一个样本使得比对出错,打印样本分析是哪个方法出错;
- 当样本数量很多时比对测试依然正确,可以确定方法a已经正确。
// 冒泡排序BubbleSort利用对数器检验
import java.util.Arrays;
public class test {
//1.测试方法a:冒泡排序BubbleSort
public static void bubbleSort(int[] arr) {
if (arr == null || arr.length < 2) {
return;
}
for (int e = arr.length - 1; e > 0; e--) {
for (int i = 0; i < e; i++) {
if (arr[i] > arr[i + 1]) {
swap(arr, i, i + 1);
}
}
}
}
public static void swap(int[] arr, int i, int j) {
arr[i] = arr[i] ^ arr[j];
arr[j] = arr[i] ^ arr[j];
arr[i] = arr[i] ^ arr[j];
}
// 2.绝对正确的方法b
public static void comparator(int[] arr) {
Arrays.sort(arr);
}
// 3.产生随即样本的产生器
public static int[] generateRandomArray(int maxSize, int maxValue) {
//长度随机
int[] arr = new int[(int) ((maxSize + 1) * Math.random())];
for (int i = 0; i < arr.length; i++) {
//内容随机
arr[i] = (int) ((maxValue + 1) * Math.random()) - (int) (maxValue * Math.random());
}
return arr;
}
// 复制数组,包括长度和内容
public static int[] copyArray(int[] arr) {
if (arr == null) {
return null;
}
int[] res = new int[arr.length];
for (int i = 0; i < arr.length; i++) {
res[i] = arr[i];
}
return res;
}
// 4.方法a和方法b比对方法(是否相同)
public static boolean isEqual(int[] arr1, int[] arr2) {
if ((arr1 == null && arr2 != null) || (arr1 != null && arr2 == null)) {
return false;
}
if (arr1 == null && arr2 == null) {
return true;
}
if (arr1.length != arr2.length) {
return false;
}
for (int i = 0; i < arr1.length; i++) {
if (arr1[i] != arr2[i]) {
return false;
}
}
return true;
}
// 打印数组元素
public static void printArray(int[] arr) {
if (arr == null) {
return;
}
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
// 把方法a和方法b比对500000来验证方法a是否正确;
public static void main(String[] args) {
int testTime = 500000;
int maxSize = 100;
int maxValue = 100;
//利用succeed验证是否出错
boolean succeed = true;
for (int i = 0; i < testTime; i++) {
int[] arr1 = generateRandomArray(maxSize, maxValue);
int[] arr2 = copyArray(arr1);
bubbleSort(arr1);
comparator(arr2);
if (!isEqual(arr1, arr2)) {
succeed = false;
break;
}
}
System.out.println(succeed ? "Nice!" : "Fucking fucked!");
//5. 如果有一个样本使得比对出错,打印样本分析是哪个方法出错;
int[] arr = generateRandomArray(maxSize, maxValue);
printArray(arr);
bubbleSort(arr);
printArray(arr);
}
}
比较器
import java.util.Arrays;
import java.util.Comparator;
public class Comparator {
public static class Student {
public String name;
public int id;
public int age;
public Student(String name, int id, int age) {
this.name = name;
this.id = id;
this.age = age;
}
}
//id升序
public static class IdAscendingComparator implements Comparator<Student> {
@Override
public int compare(Student o1, Student o2) {
return o1.id - o2.id;
}
}
//id降序
public static class IdDescendingComparator implements Comparator<Student> {
@Override
public int compare(Student o1, Student o2) {
return o2.id - o1.id;
}
}
//年龄升序
public static class AgeAscendingComparator implements Comparator<Student> {
@Override
public int compare(Student o1, Student o2) {
return o1.age - o2.age;
}
}
//年龄降序
public static class AgeDescendingComparator implements Comparator<Student> {
@Override
public int compare(Student o1, Student o2) {
return o2.age - o1.age;
}
}
//打印学生
public static void printStudents(Student[] students) {
for (Student student : students) {
System.out.println("Name : " + student.name + ", Id : " + student.id + ", Age : " + student.age);
}
System.out.println("===========================");
}
public static void main(String[] args) {
Student student1 = new Student("A", 1, 23);
Student student2 = new Student("B", 2, 21);
Student student3 = new Student("C", 3, 22);
Student[] students = new Student[] { student3, student2, student1 };
printStudents(students);
Arrays.sort(students, new IdAscendingComparator());
printStudents(students);
Arrays.sort(students, new IdDescendingComparator());
printStudents(students);
Arrays.sort(students, new AgeAscendingComparator());
printStudents(students);
Arrays.sort(students, new AgeDescendingComparator());
printStudents(students);
}
}
其他排序方法:
(1)优先队列相当于堆
PriorityQueue<Student> heap =new PriorityQueue<>(new IdAscendingComparator());
heap.add(student3);
heap.add(student2);
heap.add(student1);
while(!heap.isEmpty())
{
Student student =heap.poll();
System.out.println("Name : " + student.name + ", Id : " + student.id + ", Age : " + student.age);
}
(2)TreeSet是一个包含有序的且没有重复元素的集合
TreeSet treeSet = new TreeSet<>(new IdAscendingComparator());