简体   繁体   English

如何对数组的前半部分按升序排序,后半部分按降序排序

[英]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.我目前有一个使用 Java 的合并排序算法,但我正在努力修改它以按降序对后半部分进行排序。 It should also have a time complexity of O(n).它还应该具有 O(n) 的时间复杂度。

For example:例如:

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

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

In java 1.8+ we can do it like this.在 java 1.8+ 中,我们可以这样做。 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);
}

暂无
暂无

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

相关问题 对数组进行排序,使得上半部应在Java中按升序排列 - Sort an array such a way that First half should be in ascending order Second half should be in descending order in java 应该如何声明java比较器类以按升序和降序的第二个元素对数组进行排序 - How should java comparator class be declared to sort the array by there second element in ascending and descending order 按升序和降序对数组的 LinkedHashmap 进行排序 - Java - Sort LinkedHashmap of Array in ascending and descending order - Java 给定2个数组,如何按升序对第一个数组进行排序,并交换第二个数组的值以便与第一个数组匹配? - Given 2 arrays, how to sort the first array in ascending order, and swap the second array values so as to match with the first array? 按升序和降序对arrayList进行排序 - Sort arrayList in ascending and descending order 升序归并排序到降序 - Ascending Merge Sort to Descending Order 首先对Array By变量进行排序,然后按降序对其进行排序 - Sort Array By variable in the first then sort it descending order 如何将此数组按升序排序? - How to sort this array into ascending order? 如何比较首个元素和最后一个元素以降序对数组进行排序 - How to sort an array in descending order comparing the first element and the last 如何在java中仅使用lambda按升序和降序对整数数组进行排序 - How to sort integer array in ascending and descending order using lambda only in java
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM