快速排序
public void quickSort(int[] nums, int l, int r) {
if (l >= r) {
return;
}
int mid = partition(nums, l, r);
quickSort(nums, l, mid - 1);
quickSort(nums, mid + 1, r);
}
//填坑法
public int patition(int[] nums, int l, int r) {
int first = l, last = r, pivot = nums[first];
while (first < last) {
while (first < last && nums[last] >= pivot {
--last;
}
nums[first] = nums[last];
while (first < last && nums[first] <= pivot) {
++first;
}
nums[last] = nums[first];
}
nums[first] = pivot;
return first;
}
// https://segmentfault.com/a/1190000004410119 快排的四种写法~~
归并排序
public static void mergeSort(int[] array) {
if (array == null || array.length == 0)
return;
int[] temp = new int[array.length];
mergeSort(array, 0, array.length - 1, temp);
}
// 归并
private static void mergeSort(int array[], int first, int last, int temp[]) {
if (first < last) {
int mid = (first + last) / 2;
mergeSort(array, first, mid, temp); // 递归归并左边元素
mergeSort(array, mid + 1, last, temp); // 递归归并右边元素
mergeArray(array, first, mid, last, temp); // 再将二个有序数列合并
}
}
/**
* 合并两个有序数列
* array[first]~array[mid]为第一组
* array[mid+1]~array[last]为第二组
* temp[]为存放两组比较结果的临时数组
*/
private static void mergeArray(int array[], int first, int mid, int last, int temp[]) {
int i = first, j = mid + 1; // i为第一组的起点, j为第二组的起点
int m = mid, n = last; // m为第一组的终点, n为第二组的终点
int k = 0; // k用于指向temp数组当前放到哪个位置
while (i <= m && j <= n) { // 将两个有序序列循环比较, 填入数组temp
if (array[i] <= array[j])
temp[k++] = array[i++];
else
temp[k++] = array[j++];
}
while (i <= m) { // 如果比较完毕, 第一组还有数剩下, 则全部填入temp
temp[k++] = array[i++];
}
while (j <= n) {// 如果比较完毕, 第二组还有数剩下, 则全部填入temp
temp[k++] = array[j++];
}
for (i = 0; i < k; i++) {// 将排好序的数填回到array数组的对应位置
array[first + i] = temp[i];
}
}
插入排序
public void insertSort(int[] nums) {
if (nums == null || nums.length == 0) {
return;
}
for (int i = 1; i < nums.length - 1; i++) {
if (nums[i] < nums[i-1]) {
int j = i;
int temp = nums[i];
while (j > 0 && temp < nums[j-1]) {
nums[j] = nums[j-1];
--j;
}
nums[j] = temp;
}
}
}
冒泡排序
public void bubbleSort(int[] nums) {
for (int i = 0; i < nums.length - 1; i++) {
boolean swapped = false;
for (int j = 0; j < nums.length - i - 1; j++) {
if (nums[j] < nums[j+1]) {
int temp = nums[j+1];
nums[j+1] = nums[j];
nums[j] = temp;
}
}
if (!swapped) {
break;
}
}
}
选择排序
public void selectSort(int[] nums) {
int n = nums.length;
for (int i = 0; i < n; i++) {
int p = i;
for (int j = i + 1; j < n; j++) {
if (nums[j] < nums[p]) {
p = j;
}
}
int temp = nums[i];
nums[i] = nums[p];
nums[p] = temp;
}
}