归并排序主体运行情况如下:
归并排序算法java代码实现如下:
import java.util.Arrays; import javax.sound.midi.MidiDevice; public class MergeSort { public static void main(String[] args) { int[] a = { 1, 5, 6, 24,8,6,345,346 }; mergeSort(a, 0, a.length - 1); System.out.println("归并排序结果=" + Arrays.toString(a)); } private static void mergeSort(int[] a, int i, int j) { // TODO Auto-generated method stub int mid = (i + j) / 2; //System.out.print( mid +" "); if (i < j) { mergeSort(a, i, mid); mergeSort(a, mid + 1, j); merge(a, i, mid, j); } } private static void merge(int[] a, int low, int mid, int high) { // TODO Auto-generated method stub int i = low; int j = mid + 1; int k = 0; int[] tmp = new int[high - low + 1]; // 辅助数组 while (i <= mid && j <= high) { if (a[i] < a[j]) { tmp[k++] = a[i++]; } else { tmp[k++] = a[j++]; } } while (i <= mid) { tmp[k++] = a[i++]; } while (j <= high) { tmp[k++] = a[j++]; } for (int x = 0; x < tmp.length; x++) { a[low++] = tmp[x]; } for (int l = 0; l < tmp.length; l++) { System.out.print(tmp[l]+" "); } System.out.println(); } }
运行结果如下: