public class NatureSort {
public static void main(String[] args) {
int[] a = {4, 9, 2, 6, 1, 5, 7, 3};
int[] b = new int[8];
int len = partition(a, 8, b);
/*for(int i = 0; i < len; i++)
System.out.println(b[i]);*/
natureSort(a, 8, b, len, 0, len - 1);
System.out.print(a[0]);
for(int i = 1; i < 8; i++)
System.out.print(" " + a[i]);
System.out.println();
}
public static int partition(int[] a, int n, int[] b) {
int len = 1;
b[0] = 0;
for(int i = 1; i < n; i++) {
if(a[i] < a[i - 1])
b[len++] = i;
}
return len;
}
public static void natureSort(int[] a, int n, int[] b, int len, int left, int right) {
if(right - left > 0) {
int mid = (left + right) / 2;
natureSort(a, n, b, len, left, mid);
natureSort(a, n, b, len, mid + 1, right);
int mleft, mmid, mright;
mleft = b[left];
mmid = b[mid + 1] - 1;
if(right + 1 < len)
mright = b[right + 1] - 1;
else
mright = n - 1;
merge(a, mleft, mmid, mright);
}
}
public static void merge(int[] a, int left, int mid, int right) {
int c1 = left, c2 = mid + 1;
int c = 0;
int[] work = new int[right - left + 1];
while(c1 <= mid && c2 <= right) {
if(a[c1] < a[c2])
work[c++] = a[c1++];
else
work[c++] = a[c2++];
}
while(c1 <= mid)
work[c++] = a[c1++];
while(c2 <= right)
work[c++] = a[c2++];
for(int i = left, j = 0; i <= right; i++, j++)
a[i] = work[j];
}
}