简体   繁体   English

按插入排序[降序]

[英]Sort by insertion sort [descending]

if this code is to sort by ascending 如果此代码是按升序排序

    public static String [] selectionSort_String(String[] inList) {
   String temp;     


   for (int i=0; i<(inList.length-1); i++) {
       for (int j=i+1; j<inList.length; j++) {
           if (inList[i].compareTo(inList[j]) > 0) {
               temp = inList[i];
               inList[i] = inList[j];
               inList[j] = temp;
           }
       }
   }

   // return the sorted Array
   return inList;

How Do I get it to Sort by descending? 如何获得降序排序?

It is incredibly trivial. 这是微不足道的。 In your algorithm, you swap indicies i and j if inList[i] has a larger value than inList[j] . 在您的算法中,如果inList[i]的值大于inList[j]值,则交换索引ij Simply change the boolean logic when you swap them (ie i is smaller than j). 交换它们时只需更改布尔逻辑(即,i小于j)。

...
for (int i=0; i<(inList.length-1); i++) {
   for (int j=i+1; j<inList.length; j++) {
       if (inList[i].compareTo(inList[j]) < 0) { // <--Changing the operator to LT
           temp = inList[i];
           inList[i] = inList[j];
           inList[j] = temp;
       }
   }

The absolute easiest way to change the direction of the sort here, is to change the if-statement operator > to <. 更改排序方向的最简单方法是将if语句运算符>更改为<。

if (inList[i].compareTo(inList[j]) < 0) {

You can have a look here to see how compareTo works http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#compareTo(java.lang.String) 您可以在此处查看compareTo的工作原理http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#compareTo(java.lang.String)

只需在compareTo行中用<切换>。

You can sort using Arrays.sort and on the implementation compare object2 with object1 to invert the result. 您可以使用Arrays.sort进行排序,并在实现上将object2与object1进行比较以反转结果。

Comparator<String> comparator = new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return o2.compareTo(o1);
            }
        };

Arrays.sort(strings, comparator);

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

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