步骤:
确定分界点,mid = (l+r)/2 递归排序left、right 归并,合二为一
package base ;
import java. io. BufferedReader ;
import java. io. IOException ;
import java. io. InputStreamReader ;
public class Merge_sort {
static int n;
static int q[ ] ;
static int temp[ ] ;
public static void main ( String [ ] args) {
BufferedReader bf = new BufferedReader ( new InputStreamReader ( System . in) ) ;
try {
System . out. println ( "输入n:" ) ;
n = Integer . parseInt ( bf. readLine ( ) ) ;
q = new int [ n] ;
for ( int i = 0 ; i < n; i++ ) {
System . out. println ( "输入第" + ( i+ 1 ) + "个数据:" ) ;
q[ i] = Integer . parseInt ( bf. readLine ( ) ) ;
}
} catch ( IOException e) {
e. printStackTrace ( ) ;
}
merge_sort ( q, 0 , n- 1 ) ;
for ( int n: q) {
System . out. println ( n) ;
}
}
public static void merge_sort ( int [ ] q, int l , int r) {
if ( l>= r) return ;
int mid = ( l+ r) >> 1 ;
merge_sort ( q, l, mid) ;
merge_sort ( q, mid+ 1 , r) ;
int k = 0 ;
int i = l, j = mid + 1 ;
temp = new int [ q. length] ;
while ( i<= mid && j<= r) {
if ( q[ i] <= q[ j] ) {
temp[ k++ ] = q[ i++ ] ;
} else {
temp[ k++ ] = q[ j++ ] ;
}
}
while ( i<= mid) {
temp[ k++ ] = q[ i++ ] ;
}
while ( j<= r) {
temp[ k++ ] = q[ j++ ] ;
}
for ( i= l, j = 0 ; i<= r; i++ , j++ ) {
q[ i] = temp[ j] ;
}
}
}