归并排序

来源:互联网 发布:淘宝的等级划分 编辑:程序博客网 时间:2024/04/30 05:28
/**
*
*归并排序吧数组拆成单个,然后在进行排序合并
*/
 
public class MergeSortClass {private int[] SortOut;public void printSortedOutput() {for (int i = 0; i < this.SortOut.length; i++) {System.out.print(this.SortOut[i] + " ");}}public MergeSortClass(int[] in) {this.SortOut = this.MergeSort(in);}private int[] MergeSort(int[] i_list) {if (i_list.length == 1) {return i_list;} else {int[] listL = new int[i_list.length / 2];int[] listR = new int[i_list.length - i_list.length / 2];int Center = i_list.length / 2;for (int i = 0; i < Center; i++) {listL[i] = i_list[i];}for (int i = Center, j = 0; i < i_list.length; i++, j++) {listR[j] = i_list[i];}int[] SortedListL = MergeSort(listL);int[] SortedListR = MergeSort(listR);int[] o_list = MergeTwoList(SortedListL, SortedListR);return o_list;}}private int[] MergeTwoList(int[] listL, int[] listR) {int i = 0, j = 0;int[] o_list = new int[listL.length + listR.length];int foot = 0;while (i < listL.length && j < listR.length) {if (listL[i] <= listR[j]) {o_list[foot] = listL[i];i++;} else {o_list[foot] = listR[j];j++;}foot++;}if (i == listL.length) {while (j < listR.length) {o_list[foot++] = listR[j++];}} else { // j==listR.lengthwhile (i < listL.length) {o_list[foot++] = listL[i++];}}return o_list;}public static void main(String[] args) {int[] in = { 2, 5, 3, 8, 6, 7, 1, 4, 0, 9 };MergeSortClass msTest = new MergeSortClass(in);msTest.printSortedOutput();}}

原创粉丝点击