简体   繁体   English

不使用排序方法按正负号(正,零,负)对整数数组进行排序

[英]Sorting an int array by sign(positive, zero, negative) without sort method

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. 顺序无关紧要。

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! 在这里尝试

Actually, your code does not sort the positive numbers correctly, maybe because it's not doing enough number of iterations . 实际上,您的代码没有正确地对正数进行sort ,可能是因为它没有进行足够多的iterations To sort all the numbers (including zero), I would recommend falling back to bubble sort, eg: 要对所有数字进行排序(包括零),我建议退回到冒泡排序,例如:

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. 另外,由于只对实际数组进行了更改,因此我们不需要return任何内容。

Edit 编辑

Another solution to sort the array with one for loop, (ie O(n) complexity): 使用for循环对数组进行排序的另一种解决方案(即O(n)复杂度):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM