import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class MergeSort {
public static void main(String[] args) {
int size = 0;
int[] A = null;
// Make pipe from stardard input..
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
try {
// Ask size of a list.
System.out.print("Enter the size of integer list to be sorted: ");
size = Integer.parseInt(stdin.readLine());
if ( size < 1 ) {
System.out.println("Size should be postive integer");
System.exit(0);
}
A = new int[size];
for ( int i=0; i < size ; i++ ) {
System.out.println("Enter an integer(" + (i+1) + "): ");
A[i] = Integer.parseInt(stdin.readLine());
}
System.out.print("Original list : <");
for ( int i=0; i < size-1 ; i++ ) {
System.out.print(A[i] + ", ");
}
System.out.println(A[size-1] + ">");
mergeSort(A, 0, size-1);
System.out.print("Sorted list : <");
for ( int i=0; i < size-1 ; i++ ) {
System.out.print(A[i] + ", ");
}
System.out.println(A[size-1] + ">");
} catch(NumberFormatException nfe) {
System.out.println("Input should be numbers");
} catch(IOException ioe) {
System.out.println("IOException happens");
} finally {
}
}
public static void mergeSort(int[] A, int p, int r) {
if ( p < r ) {
mergeSort(A, p, (int)((p+r)/2));
mergeSort(A, (int)((p+r)/2)+1, r);
merge(A, p, (int)((p+r)/2), r);
}
}
public static int[] merge(int[] A, int p, int q, int r) {
int j=p, k=q+1;
int[] result = new int[r-p+1];
for ( int i=0; i < r-p+1; i++ ) {
if ( j <= q && k <= r ) {
if ( A[j] <= A[k] ) {
result[i] = A[j];
j++;
} else {
result[i] = A[k];
k++;
}
/* All elements of A is removed */
} else if ( j > q ) {
result[i] = A[k];
k++;
/* All elements of B is removed */
} else if ( k > r ) {
result[i] = A[j];
j++;
}
}
for ( int i=0; i < result.length ; i++ ) {
A[p+i] = result[i];
}
return A;
}
}
이전 글 : SQL Server 리포팅 서비스 소개
다음 글 : JBoss 리모팅 사용하기
최신 콘텐츠