Home > other >  Java implementation merging algorithm
Java implementation merging algorithm

Time:04-23

The so-called merge algorithm, is a kind of partition; The data grouping, and then sorting, finally together;
The following is a code, the use of Comparable, simple and direct,
 
The import org. Junit. Test;

Import the Java. Util. Arrays;

Public class Merge {
Private static Comparable [] assist;
Private static Boolean greater (Comparable, v, Comparable, w) {
Return to v.com pareTo (w) & lt; 0;
}
Public static void sort (Comparable [] a) {
Assist=new, Comparable [a. ength];
Int lo=0;
Int hi=a. ength - 1;
Sort (a, lo, hi);
}
A private static void sort (Comparable [], int lo, int hi) {
If (hireturn;
}
Int mid=lo + (hi - lo)/2;
Sort (a, lo, mid);
Sort (a, mid + 1, hi);
Merge (a, lo, mid, hi);
}
A private static void merge (Comparable [], int lo, int mids, int hi) {
Int I=lo;
Int p1=lo;
Int p2=mid + 1;
While (p1 & lt;=mid& & The p2 & lt;={hi)
If (greater (a [p1], a [p2])) {
Assist=[i++], a [p1 + +];
} else {
Assist=[i++], a [p2 + +];
}
}
While (p1 & lt; Mid)={
Assist=[i++], a [p1 + +];
}
While (p2 & lt;={hi)
Assist=[i++], a [p2 + +];
}
For (int index=lo; The index & lt;=the hi; Index++) {
A [index]=assist [index];
}
}
@ Test
Public void TestMerge () {
Comparable [] a=new Comparable [] {9,5,6,7,8,4,3,2,1,0};
System. The out. Println (" is to sort an array "+ Arrays. ToString (a));
Sort (a);
System.out.println(Arrays.toString(a));
}
}
  • Related