package array;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class GenerateArray {
public static void main(String[] args) {
createArray(3);
}
static class Number implements Comparable<Number>{
int number;
int index;
@Override
public int compareTo(Number o) {
if(this.number < o.number){
return 1;
}else if(this.number == o.number){
return 0;
}
return -1;
}
enum Direction {
Left,
Right
}
Direction direction;
public Number(int num){
this.number = num;
index = num-1;
direction = Direction.Left;
}
}
public static void createArray(int n){
if(n <= 1){
System.out.println("1");
return;
}
List<Number> numbs = new ArrayList<Number>();
for(int i=0; i<n; i++){
numbs.add(new Number(i+1));
System.out.print((i+1)+" ");
}
System.out.println();
for(;;){
boolean flag = true;
List<Number> mover = new ArrayList<Number>();
if(numbs.get(0).direction != Number.Direction.Left){
if(numbs.get(0).number > numbs.get(1).number){
mover.add(numbs.get(0));
flag = false;
}
}
for(int i=1; i<n-1; i++){
switch (numbs.get(i).direction){
case Left:
if(numbs.get(i-1).number < numbs.get(i).number){
mover.add(numbs.get(i));
flag = false;
}
break;
case Right:
if(numbs.get(i-1).number < numbs.get(i).number){
mover.add(numbs.get(i));
flag = false;
}
break;
}
}
if(numbs.get(n-1).direction != Number.Direction.Right){
if(numbs.get(n-1).number > numbs.get(n-2).number){
mover.add(numbs.get(n-1));
flag = false;
}
}
if(!flag) {
Collections.sort(mover);
int bigNumbIndex = mover.get(0).index;
Number big,small;
switch (numbs.get(bigNumbIndex).direction){
case Left:
numbs.get(bigNumbIndex).index = bigNumbIndex-1;
numbs.get(bigNumbIndex-1).index = bigNumbIndex;
big = numbs.get(bigNumbIndex);
small = numbs.get(bigNumbIndex-1);
numbs.remove(bigNumbIndex - 1);
numbs.remove(bigNumbIndex - 1);
numbs.add(big.index,big);
numbs.add(small.index,small);
bigNumbIndex--;
break;
case Right:
numbs.get(bigNumbIndex).index = bigNumbIndex+1;
numbs.get(bigNumbIndex+1).index = bigNumbIndex;
big = numbs.get(bigNumbIndex);
small = numbs.get(bigNumbIndex+1);
numbs.remove(bigNumbIndex);
numbs.remove(bigNumbIndex);
numbs.add(small.index,small);
numbs.add(big.index,big);
bigNumbIndex++;
break;
}
for(int i=0; i<n; i++){
if(i != bigNumbIndex && numbs.get(i).number > numbs.get(bigNumbIndex).number){
numbs.get(i).direction = numbs.get(i).direction == Number.Direction.Left ? Number.Direction.Right
: Number.Direction.Left;
}
}
for(int i=0; i<n; i++){
System.out.print(numbs.get(i).number +" ");
}
System.out.println();
}else{
break;
}
}
}
}
生成序列
最新推荐文章于 2020-12-09 17:46:08 发布