标签:排序 div ble ini index select sel quic cts
1、冒泡排序,时间复杂度:最好:T(n) = O(n) ,情况:T(n) = O(n2) ,平均:T(n) = O(n2)
public int[] bubbleSort(int[] nums) { if (nums.length < 2) { return nums; } for (int i = 0; i < nums.length; i++) { for (int j = 0; j < nums.length - 1 - i; j++) { if (nums[j] > nums[j + 1]) { int tem = nums[j]; nums[j] = nums[j + 1]; nums[j + 1] = tem; } } } return nums; }
2、选择排序,时间复杂度:最好:T(n) = O(n2) ,最差:T(n) = O(n2) ,平均:T(n) = O(n2)
public int[] selectSort(int[] nums) { if (nums.length < 2) { return nums; } for (int i = 0; i < nums.length - 1; i++) { int minIndex = i; for (int j = i + 1; j < nums.length; j++) { if (nums[minIndex] > nums[j]) { minIndex = j; } } if (minIndex != i) { int tem = nums[i]; nums[i] = nums[minIndex]; nums[minIndex] = tem; } } return nums; }
3、插入排序,时间复杂度:最好:T(n) = O(n) ,情况:T(n) = O(n2) ,平均:T(n) = O(n2)
public int[] insertSort(int[] nums) { if (nums.length < 2) { return nums; } for (int i = 0; i < nums.length - 1; i++) { int cur = nums[i + 1]; int per = i; while (per >= 0 && nums[per] > cur) { nums[per + 1] = nums[per]; per--; } nums[per + 1] = cur; } return nums; }
4、快速排序,时间复杂度:最好:T(n) = O(nlogn) ,最差:T(n) = O(n2), 平均:T(n) = O(nlogn)
public int[] quickSort(int[] nums) { if (nums.length < 2) { return nums; } sort(nums, 0, nums.length - 1); return nums; } private void sort(int nums[], int low, int high) { int l = low, h = high; int povit = nums[low]; while (l < h) { while (l < h && nums[h] >= povit) h--; if (l < h) { nums[l] = nums[h]; l++; } while (l < h && nums[l] <= povit) l++; if (l < h) { nums[h] = nums[l]; h--; } } nums[l] = povit; if (l - 1 > low) sort(nums, low, l - 1); if (h + 1 < high) sort(nums, h + 1, high); }
标签:排序 div ble ini index select sel quic cts
原文地址:https://www.cnblogs.com/zhi-leaf/p/10722576.html