归并排序
Posted Tianyiya H.T.W
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了归并排序相关的知识,希望对你有一定的参考价值。
import java.util.Scanner; public class Main { public static void sort(int [] arr,int left,int right) { if (left >= right) { return; } int m = (left + right) >>> 1; sort(arr, left, m); sort(arr, m + 1, right); int[] tmp = new int[right - left + 1]; int i = left, j = m + 1, index = 0; while (i <= m && j <= right) { if (arr[i] <= arr[j]) { tmp[index ++] = arr[i ++]; } else { tmp[index ++] = arr[j ++]; } } while (i <= m) { tmp[index ++] = arr[i ++]; } while (j <= right) { tmp[index ++] = arr[j ++]; } for (int k = left; k <= right; ++ k) { arr[k] = tmp[k - left]; } } public static void main(String[] args) { Scanner in = new Scanner(System.in); while (in.hasNext()) { int n = in.nextInt(); int[] arr = new int[n]; for (int i = 0; i < n; ++ i) { arr[i] = in.nextInt(); } sort(arr, 0, n - 1); System.out.print(arr[0]); for (int i = 1; i < n; ++ i) { System.out.print(" " + arr[i]); } System.out.println(); } } }
心之所向,素履以往 生如逆旅,一苇以航
❤️数据结构入门❤️(4 - 4)- 归并排序
以上是关于归并排序的主要内容,如果未能解决你的问题,请参考以下文章