java 实现合并排序
1 package How; 2 3 import java.io.BufferedReader; 4 import java.io.BufferedWriter; 5 import java.io.FileReader; 6 import java.io.FileWriter; 7 import java.io.IOException; 8 import java.lang.reflect.Array; 9 import java.util.Random; 10 11 import org.omg.PortableInterceptor.DISCARDING; 12 13 public class bin_1 14 { 15 public static void main(String[] args) 16 { 17 try 18 { 19 mergesortSort myMergesortSort=new mergesortSort(); 20 myMergesortSort.display(); 21 } catch (IOException e) 22 { 23 // TODO Auto-generated catch block 24 e.printStackTrace(); 25 } 26 } 27 } 28 class mergesortSort 29 { 30 int size=6; 31 int []array; 32 int []temp; 33 BufferedWriter fout_1; 34 BufferedWriter fout_2; 35 //准备数据 36 public mergesortSort() throws IOException 37 { 38 fout_1=new BufferedWriter(new FileWriter("noOrder.txt")); 39 fout_2=new BufferedWriter(new FileWriter("inOrder.txt")); 40 Random random=new Random(); 41 array=new int[size]; 42 this.temp=new int[size]; 43 for(int i=0; i<size; i++) 44 { 45 array[i]=random.nextInt(100); 46 fout_1.write(array[i]+""); 47 fout_1.newLine(); 48 } 49 fout_1.flush(); 50 mergesort( 0, size-1); 51 } 52 //方便调用 53 public mergesortSort(int []array, int l, int r ) throws IOException 54 { 55 fout_1=new BufferedWriter(new FileWriter("noOrder.txt")); 56 fout_2=new BufferedWriter(new FileWriter("inOrder.txt")); 57 this.array=array; 58 this.temp=new int[l-r+1]; 59 mergesort( l, r); 60 } 61 public mergesortSort(int []array) throws IOException 62 { 63 fout_1=new BufferedWriter(new FileWriter("noOrder.txt")); 64 fout_2=new BufferedWriter(new FileWriter("inOrder.txt")); 65 this.array=array; 66 this.temp=new int[array.length]; 67 mergesort( 0, array.length-1); 68 } 69 public void mergesort(int l, int r) 70 { 71 if(l<r) 72 { 73 int m=(l+r)/2; 74 mergesort( l, m); 75 mergesort( m+1, r); 76 merge( l, m, r); 77 } 78 } 79 public void merge(int l, int m, int r) 80 { 81 int p=l; 82 int q=m+1; 83 int k=0; 84 System.out.println("p="+p); 85 System.out.println("q="+q); 86 while(p<=m&&r>=q) 87 { 88 if(array[p]<=array[q]) //谁小谁先进 89 { 90 temp[k++]=array[p]; 91 p++; 92 } 93 else 94 { 95 temp[k++]=array[q]; 96 q++; 97 } 98 System.out.println(""+array[k]); 99 } 100 if(p<=m) 101 { 102 for(int i=p; i<=m; i++) 103 { 104 temp[k++]=array[i]; 105 } 106 } 107 else 108 { 109 for(int i=q; i<=r; i++) 110 { 111 temp[k++]=array[i]; 112 } 113 } 114 //复制 这里比较容易出错 115 for(int i=0; i<k; i++) 116 { 117 array[l++]=temp[i]; 118 } 119 } 120 public void display() throws IOException 121 { 122 123 for(int i=0; i<array.length; i++) 124 { 125 fout_2.write(""+array[i]); 126 fout_2.newLine(); 127 } 128 fout_2.flush(); 129 } 130 }
运行结果