简体   繁体   中英

How to sort first half of an array in ascending order and second half in descending order

I currently have a Merge Sort algorithm up using Java but I am struggling with modifying it to sort the second half in descending order. It should also have a time complexity of O(n).

For example:

Input: 34, 12, 7, 43, 55, 97, 41, 28, 2, 62

Output: 2, 7, 12, 28, 34, 97, 62, 55, 43, 41

In java 1.8+ we can do it like this. we can optimize it further. :)

public static void main(String[] args) {
    Stream<Integer> streamObj = Stream.of(34, 12, 7, 43, 55, 97, 41, 28, 2, 62);
    List<Integer> list1 = streamObj.collect(Collectors.toList());
    int middleIndex = list1.size()/2;
    System.out.println(middleIndex);
    List<Integer> firstHalf = list1.subList(0,middleIndex).stream().sorted().collect(Collectors.toList());
    List<Integer> secondHalf = list1.subList(middleIndex,list1.size()).stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
    System.out.println("firstHalf"+firstHalf+"\nsecondHalf"+secondHalf);
    firstHalf.addAll(secondHalf);
    System.out.println(firstHalf);
}

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