标签:递归 sys string mergesort info 技术 一起 -- rgs
归并排序属于稳定排序,时间复杂度为O(nlogn)
思路:采用分治策略,将问题分成一些小的问题然后递归求解,治的部分是将分的部分得到的答案和在一起,即为分而治之
过程:这里用图来显示比较直观
import java.util.Arrays; public class MergeSort { public static void main(String[] args) { int arr[] = {8, 4, 5, 7, 1, 3, 6, 2}; int temp[] = new int[arr.length]; mergeSort(arr, 0, arr.length - 1, temp); System.out.println(Arrays.toString(arr)); } public static void mergeSort(int[] arr, int left, int right, int[] temp) { if (left < right) { int mid = (left + right) / 2; mergeSort(arr, left, mid, temp); mergeSort(arr, mid + 1, right, temp); merge(arr,left,mid,right,temp); } } public static void merge(int[] arr, int left, int mid, int right, int[] temp) { int i = left; int j = mid + 1; int t = 0; while (i <= mid && j <= right) { if (arr[i] < arr[j]) { temp[t] = arr[i]; t++; i++; } else { temp[t] = arr[j]; t++; j++; } } while (i <= mid) { temp[t] = arr[i]; t++; i++; } while (j <= right) { temp[t] = arr[j]; t++; j++; } t = 0; int tempLeft = left; System.out.println(tempLeft+"---"+right); while (tempLeft <= right) { arr[tempLeft] = temp[t]; t++; tempLeft++; } } }
标签:递归 sys string mergesort info 技术 一起 -- rgs
原文地址:https://www.cnblogs.com/bingbug/p/12122885.html