Java:对数组进行排序(第2部分)

时间:2013-07-02 04:22:30

标签: java

我理解如何按升序和降序对数组进行排序,但是我正在尝试创建一个特定的模式。例如,我有一个随机顺序的数组。我如何在模式中对此数组进行排序? “最小,最大,第二小,第二大,第三大,第三大......”等等任何想法?

public class Test2 {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    int[] array = {1,4,2,6,9,3,65,77,33,22};
    for(int i = 0; i < array.length; i++){
        System.out.print(" " + array[i]);
}     
    wackySort(array);

}


public static void wackySort(int[] nums){
    int sign = 0;
    int temp = 0;
    int temp2 = 0;
//This sorts the array
    for (int i = 0; i < nums.length; i++){
        for (int j = 0; j < nums.length -1; j++){
            if (nums[j] > nums[j+1]){
                temp = nums[j];
                nums[j] = nums[j+1];
                nums[j+1] = temp;

        }
    }

}
// This prints out the new array
            System.out.println();
            for(int i = 0; i < nums.length; i++){
                System.out.print(" " + nums[i]);
            }
            System.out.println();

//This part attempts to fix the array into the order I want it to
            int firstPointer = 0;
            int secondPointer = nums.length -1;
            int[] newarray = new int[nums.length];
    for (int i = 0; i < nums.length -1; i+=2){
        newarray[i] = nums[firstPointer++];
                    newarray[i] = nums[secondPointer--];
} 
            for(int i = 0; i < newarray.length; i++){
                System.out.print(" " + newarray[i]);
}


}
}

1 个答案:

答案 0 :(得分:1)

您需要编写自己的Comparator来实现此目的。研究这篇关于Java Object Sorting Example (Comparable And Comparator)的文章。它会对你有所帮助。