import java.awt.List;
import java.util.LinkedList;
import java.util.Scanner;
public class Naturesort {
public static void main(String[] args) {
int[] a = read();
print(a);
int[] b = getCount(a);
sort(a,b);
print(a);
}
public static int[] read(){
LinkedList<Integer> arr = new LinkedList<Integer>();
Scanner s = new Scanner(System.in);
int num;
while((num = s.nextInt()) != 0){
arr.add(num);
}
Integer[] n = arr.toArray(new Integer[0]);
int[] a = new int[n.length];
for(int i=0; i < n.length; i ++)
{
a[i] = n[i].intValue();
}
return a;
}
public static void print(int[] n){
for(int i =0; i < n.length ; i++){
System.out.print(n[i]+" ");
}
System.out.println();
}
public static int[] getCount(int[] n){
int i = 0,j = -1,count = 0;
int[] b = new int[n.length+1];//b数组用来记录分成数组的大小,下表标值+1用来表示数组的个数
while(i < (n.length -1)){
if(n[i] <= n[i+1]){
i++;
}else{
b[count] = i - j;
count++;
j = i;
i++;
}
}
b[count++] = n.length - j - 1;
if(count == 1){
System.out.println("排序结束!");
print(n);
System.exit(0);
}
print(b);
return b;
}
public static void sort(int[] n,int[] b){
int k = 0 ,count = 0;
int j =0,p = 0, q = 0;
int indexC = 0, indexD = 0;
while(b[k++] != 0){
count++;
}
for(int i = count/2;i >= 1;i--){
int[] c = new int[b[j]];
int[] d = new int[b[j+1]];
indexC = 0;
indexD = 0;//注意下标置零,哼重要!
for(;indexC < c.length ;indexC++){
c[indexC] = n[p++];
}
for(;indexD < d.length ;indexD++){
d[indexD] = n[p++];
}
indexC = 0;
indexD = 0;//注意下标置零,很重要!!
while(indexC < c.length && indexD < d.length){
if(c[indexC] <= d[indexD]){
n[q++] = c[indexC++];
}else{
n[q++] = d[indexD++];
}
}
if(indexC < c.length)
{
for(;indexC < c.length ; indexC++){
n[q++] = c[indexC];
}
}else if(indexD < d.length){
for(;indexD < d.length;indexD++){
n[q++] = d[indexD];
}
}
j = j+ 2;
}
print(n);
b = getCount(n);
sort(n,b);
}
}
小白笔记---------------------自然合并排序算法(感谢bob的指导)
最新推荐文章于 2022-04-05 02:17:01 发布