归并排序

来源:互联网 发布:女生一开始很热情知乎 编辑:程序博客网 时间:2024/06/05 07:38
package com.lin.test;public class Sort {static void merge(int a[], int first, int mid, int last, int[] temp) {int i = first, j = mid + 1, k = 0;while (i <= mid && j <= last) {if (a[i] <= a[j]) {temp[k++] = a[i++];} else {temp[k++] = a[j++];}}while (i <= mid) {temp[k++] = a[i++];}while (j <= last) {temp[k++] = a[j++];}for (i = 0; i < k; i++) {a[first + i] = temp[i];}}static void mergeSort(int a[], int first, int last, int temp[]) {if (first < last) {int mid = (first + last) / 2;mergeSort(a, first, mid, temp);mergeSort(a, mid + 1, last, temp);merge(a, first, mid, last, temp);}}public static void main(String[] args) {int a[] = { 3, 2, 5, 7, 8, 9, 4, 1, 0, 4, 6 };int[] temp = new int[a.length];mergeSort(a, 0, a.length - 1, temp);for (int i : a) {System.out.print(i + " ");}}}

0 0