Reputation: 33
public static int[] sortBySign(int[] nums){
int startIndex = 0;
int endIndex = nums.length - 1;
while(startIndex < endIndex){
while(nums[startIndex] < 0){
startIndex++;
}
while(nums[endIndex] > 0){
endIndex--;
}
int temp = nums[startIndex];
nums[startIndex] = nums[endIndex];
nums[endIndex] = temp;
startIndex++;
endIndex--;
}
return nums;
}
My code works for sorting positive and negative numbers but I'm not sure how to sort the zeroes as well. The negatives should be on the left side, zeroes in the middle, and positives on the right side. The order does not matter.
Upvotes: 0
Views: 1000
Reputation: 30819
Actually, your code does not sort
the positive numbers correctly, maybe because it's not doing enough number of iterations
. To sort all the numbers (including zero), I would recommend falling back to bubble sort, e.g.:
public static void sort(int[] array) {
for (int i = 0; i < array.length; i++) {
for (int j = 1; j < (array.length - i); j++) {
if (array[j - 1] > array[j]) {
int temp = array[j - 1];
array[j - 1] = array[j];
array[j] = temp;
}
}
}
}
Also, we don't need to return
anything as the changes are being made to the actual array only.
Edit
Another solution to sort the array with one for loop, (i.e. O(n)
complexity):
public static void sort(int[] array) {
boolean continue = false;
for (int i = 0; i < array.length - 1; i++) {
if (array[i] < array[i + 1]) {
int temp = array[i];
array[i] = array[i + 1];
array[i + 1] = temp; // swap values
continue = true;
}
if (i == array.length - 2 && again) {
i = 0;
continue = false;
}
}
}
Upvotes: 1
Reputation: 22360
Using a auxiliary swap method you could handle the zeroes like so:
public static int[] sortBySign(int[] array) {
int counter = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] < 0) {
swap(array, counter++, i);
}
}
for (int i = counter; i < array.length; i++) {
if (array[i] == 0) {
swap(array, counter++, i);
}
}
return array;
}
private static void swap(int array[], int index1, int index2) {
int temp = array[index2];
for (int i = index2; i > index1; i--) {
array[i] = array[i - 1];
}
array[index1] = temp;
}
Try it here!
Upvotes: 1