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);
}
5、归并排序,时间复杂度:最好:T(n) = O(n) ,最差:T(n) = O(nlogn) ,平均:T(n) = O(nlogn)
public int[] mergeSort(int[] nums) {
if (nums.length < 2) {
return nums;
}
int mid = nums.length / 2;
int[] nums1 = Arrays.copyOfRange(nums, 0, mid);
int[] nums2 = Arrays.copyOfRange(nums, mid, nums.length);
return merge(mergeSort(nums1), mergeSort(nums2));
} private int[] merge(int[] nums1, int[] nums2) {
int[] back = new int[nums1.length + nums2.length];
for (int i = 0, m = 0, n = 0; i < back.length; i++) {
if (m == nums1.length) {
back[i] = nums2[n++];
} else if (n == nums2.length) {
back[i] = nums2[m++];
} else if (nums1[m] < nums2[n]) {
back[i] = nums1[m++];
} else {
back[i] = nums2[n++];
}
}
return back;
}