Python: Sorting array with custom pattern
Posted
by
Binka
on Stack Overflow
See other posts from Stack Overflow
or by Binka
Published on 2013-07-02T22:29:33Z
Indexed on
2013/07/02
23:05 UTC
Read the original article
Hit count: 146
python
In my little project here I have sorted a list in decending order, however, my goal is to sort it in this custom pattern. (largest -> smallest -> next largest -> next smallest ->)etc. In java I was able to do this like this... My goal is to do the same thing but in python, except backwards. Any ideas on how to convert that last for loop that does the wackysort into python and make it go backwards?
public static void wackySort(int[] nums){
//first, this simply sorts the array by ascending order.
int sign = 0;
int temp = 0;
int temp2 = 0;
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;
}
}
}
//prepare for new array to actually do the wacky sort.
System.out.println();
int firstPointer = 0;
int secondPointer = nums.length -1;
int[] newarray = new int[nums.length];
int size = nums.length;
//for loop that increments by two taking second slot replacing the last (n-1) term
for (int i = 0; i < nums.length -1; i+=2){
newarray[i] = nums[firstPointer++];
newarray[i+1] = nums[secondPointer--];
}
//storing those values back in the nums array
for (int i = 0; i < nums.length; i++){
nums[i] = newarray[i];
} }
© Stack Overflow or respective owner