簡體   English   中英

在不使用排序算法的情況下,如何在Java中對數組進行排序,而忽略其他值?

[英]How do you sort out an array in java without using a sorting algorithm, while ignoring other values?

int timeTakenInSeconds[] = {600, -1, 500, 430, 412, -1, 0, 0, 0};

我想將此數組從最小到最大排序。 很簡單,問題是我需要忽略-1和0。我的想法是使用冒泡排序對數組進行排序並將其放置在新數組中。 但是我發現在忽略0-1時很難對這個數組進行排序。

數組還有些陌生,所以我想知道是否有人提出建議?

我建議您考慮我的緊湊型解決方案(Java 8)。

Arrays.stream(timeTakenInSeconds)        // turn the array into the stream
      .filter(i -> i != 0 && i != -1)    // throw away 0 and -1
      .sorted()                          // make a sorted order by default
      .toArray();                        // put into an array

第二部分類似於第一部分。 然后,要合並2個數組,可以使用Apache的ArrayUtils.addAll(T[], T...)

編輯已更新,可以按升序對正整數進行排序,並且按降序對小於或等於0的整數進行排序。
使用Integer比較器:

    int timeTakenInSeconds[] = {600, -1, 500, 430, 412, -1, 0, 0, 0};
    Comparator<Integer> comparator = Integer::compare;

    //split the positive and negative integers since they'll be sorted differently.
    //Ascending order is the easiest.
    int[] positiveInts = IntStream.of(timeTakenInSeconds).filter(i -> i > 0).sorted().toArray();
    int[] negativeInts = IntStream.of(timeTakenInSeconds).filter(i -> i <= 0).toArray();

    //And now for discending order for negative integers.
    List<Integer> list = IntStream.of(negativeInts).boxed().collect(Collectors.toList());
    Integer[] sortedNegative = list.stream().sorted(comparator.reversed()).toArray(Integer[]::new);

    //Now overwrite timeTakenInSeconds with the correct values.
    int i = 0;
    for (int val : positiveInts) {
        timeTakenInSeconds[i] = val;
        i++;
    }
    for (int j = 0; j < sortedNegative.length; j++) {
        timeTakenInSeconds[i] = sortedNegative[j];
        i++;
    }

打印:

for (int j : timeTakenInSeconds) {
        System.out.print(j + " ");
}

樣品運行:

run:
412 430 500 600 0 0 0 -1 -1 
BUILD SUCCESSFUL (total time: 0 seconds)

過濾,然后自己進行排序:

int[] newArray = Arrays.stream(timeTakenInSeconds).filter(i -> i > 0).toArray();
customBubbleSort(newArray);

這是一個對數組進行排序的解決方案,不需要使用Java最新版本中的復雜功能。

public static void weirdSort(int arr[]) {
    int zeros = 0;
    int minusOnes = 0;
    int index = 0;
    for (int a : arr) {
        switch (a) {
            case 0:
                zeros++;
                break;
            case -1:
                minusOnes++;
                break;
            default:
                arr[index++] = a;
        }
    }
    for (int i = 0; i < zeros; i++)
        arr[index++] = 0;
    for (int i = 0; i < minusOnes; i++)
        arr[index++] = -1;
    Arrays.sort(arr, 0, arr.length - zeros - minusOnes);    // Replace with bubble sort
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM