手撕快排与归并
作者:互联网
快速排序代码
public class QuickSort {
public static void main(String[] args) {
int[] arr = {2,3,5,11,2,3,8,6,6,6};
System.out.println(Arrays.toString(quickSort(arr, 0, arr.length - 1)));
}
public static int[] quickSort(int[] nums, int left, int right) {
int l = left;
int r = right;
int pivot = nums[(l + r) / 2];
while (l < r) {
while (nums[l] < pivot) {
l++;
}
while ((nums[r] > pivot)) {
r--;
}
if(l >= r) {
break;
}
int temp = nums[r];
nums[r] = nums[l];
nums[l] = temp;
if (nums[r] == pivot) {
r--;
}
if (nums[l] == pivot) {
l++;
}
}
if (l == r) {
l++;
r--;
}
if (left < r) {
quickSort(nums, left, r);
}
if (l < right) {
quickSort(nums, l, right);
}
return nums;
}
}
归并排序
public class MergeSort {
public static void main(String[] args) {
int[] arr = {2,3,5,11,2,3,8,6,6,6};
int[] temp = new int[arr.length];
merge(arr,0 , arr.length - 1, temp);
System.out.println(Arrays.toString(arr));
}
public static long[] merge(int[] nums, int left, int right, int[] temp) {
if (left < right) {
int mid = (left + right) / 2;
merge(nums, left, mid, temp);
merge(nums, mid + 1, right, temp);
// 向左递归
mergeSort(nums, left, right, mid, temp);
}
return new long[0];
}
public static void mergeSort(int[] nums, int left, int right, int mid, int[] temp) {
int i = left;
int j = mid + 1;
int t = 0;
// 拆分数组到另一个数组中
while (i <= mid && j <= right) {
if (nums[i] < nums[j]) {
temp[t] = nums[i];
t++;
i++;
} else {
temp[t] = nums[j];
t++;
j++;
}
}
// 将原数组中剩余的数据添加到 temp 数组
while (i <= mid) {
temp[t] = nums[i];
t++;
i++;
}
while (j <= right) {
temp[t] = nums[j];
t++;
j++;
}
// 将临时数组 copy 到原来的数组
t = 0;
int tempLeft = left;
while (tempLeft <= right) {
nums[tempLeft] = temp[t];
tempLeft++;
t++;
}
}
}
标签:归并,right,temp,nums,int,++,快排,left 来源: https://blog.csdn.net/qq_45726143/article/details/123613127