* 一个小面试题:
* There is an array 2,10,11,4,21,5,7,6,19,15,please sort them with below order
* The maximum + the minimum + the second-largest one + the second-smallest one + ...
package main;
public class SortArray {
/**
* 一个小面试题:
* There is an array 2,10,11,4,21,5,7,6,19,15,please sort them with below order
* The maximum + the minimum + the second-largest one + the second-smallest one + ...
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
/*
* 解题思路:
* 先把数组按从大到小排序
* 21,19,15,11,10,7,6,5,4,2
* 然后一次按最小序号取出,放到一个新数组的0,2,4,6序号对应的数组位置中
* 同理,倒着取一次,放到新数组的1,3,5,7序号对应的数组位置中
*/
int [] iArray = {2,10,11,4,21,5,7,6,19,15};
int [] iOrderArray = new int[iArray.length];
/**
* 冒泡排序,按从大到小排序
*/
for(int i=0;i<iArray.length;i++){
int temp =0;
for(int j=i+1;j<iArray.length;j++){
if(iArray[i]<iArray[j]){
temp = iArray[i];
iArray[i] = iArray[j];
iArray[j] = temp;
}
}
}
System.out.print("用冒泡排序后:");
for(int i=0;i<iArray.length;i++){
System.out.print(iArray[i]+",");
}
System.out.print("\r\n");
/**
* 将排好序的数组
* 将数组的前一半,正序,按序号从小到大放入新数组的 0, 2, 4,index...序号中
* 同理,将数组的后一半,倒序,按序号从大到小放入新数组的 0+1, 2+1, 4+1,index+1...序号中
*
* 注意:数组 ArrayIndexOutOfBoundsException 新数组要限制在范围内index<iArray.length
* 注意:要考虑到数组中的个数 奇数个 和偶数个 要通用
*/
//方法一:分两步实现
int maxindex = 0;
for(int j=0;j<=(iArray.length)/2 && maxindex<iArray.length;j++){
iOrderArray[maxindex] = iArray[j];
maxindex +=2;
}
int minindex = 1;
for(int h=iArray.length-1;h >= iArray.length/2 && minindex<iArray.length;h--){
iOrderArray[minindex] = iArray[h];
minindex +=2;
}
System.out.print("方法一排序后:");
for(int i=0;i<iArray.length;i++){
System.out.print(iOrderArray[i]+",");
}
System.out.println();
//方法二:一步实现
int index = 0;
for(int j=0;j<=(iArray.length)/2 && index < iArray.length-1;j++){
iOrderArray[index] = iArray[j];
iOrderArray[index+1] = iArray[iArray.length-1-j];
index +=2;
}
System.out.print("方法二排序后:");
for(int i=0;i<iArray.length;i++){
System.out.print(iOrderArray[i]+",");
}
}
}