简体   繁体   中英

Sorting an array in ascending order that contains null values

I need to sort an array that contains null values , The null values represent invalid data that i have set to null but cannot be simply removed from the array as they represent an invalid piece of data The null values must be kept in place ie sort all other values except the null values The error that is thrown is a NullPointerException on the call to Arrays.sort();

     public static double getMedian(Double[] values) {
     Double[] copy = Arrays.copyOf(values, values.length);
     Arrays.sort(copy);
     double median;
     if (copy.length % 2 == 0)
        median = (copy[copy.length / 2] + copy[copy.length / 2 - 1]) / 2;
     else
        median = copy[copy.length / 2];
     return median;
}

All help and/or suggestions are greatly appreciated.

Add a comparator and then return the appropriate sign, to indicate less than, equal or greater than. For example:

class MyComparator<Double> implements Comparator {
    // change value to -1 to inverse sort direction.
    var direction = 1;

    public int compare(Double o1, Double o2) {
        int sign = 0;
        if (o1 == null) {
           sign = -1;
        } else if (o2 == null) {
           sign = +1;
        } else {
           sign = o1.compareTo(o2);
        }       
        return sign * direction;
    }

}

Arrays.sort(copy, new MyComparator());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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