-5

I understand how to sort an array by ascending and descending order, but there is a specific pattern I'm trying to create. For example, I have an array in a random order. How would I sort this array in the pattern? "smallest, largest, second smallest, second largest, thrid smallest, third largest..." etc Any ideas?

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]);
}


}
}
3

1 Answer 1

1

You need to write your own Comparator to achieve this. Study this article about Java Object Sorting Example (Comparable And Comparator). it will be helpful to you.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.