java 确定数组列表是否已排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17500391/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 02:11:22  来源:igfitidea点击:

Determines if the array list is sorted

javasortingoutput

提问by nazar_art

I need to estimate if the array list is sorted (don't sort).

我需要估计数组列表是否已排序(不排序)。

When Strings are sorted, they are in alphabetical order. I try to use compareTo()method to determine which string comes first

当字符串被排序时,它们是按字母顺序排列的。我尝试使用compareTo()方法来确定哪个字符串先出现

And return true if the array list is sorted, else false.

如果数组列表已排序,则返回 true,否则返回 false。

Code:

代码:

public boolean isSorted()
{
    boolean sorted = true;        
    for (int i = 1; i < list.size(); i++) {
        if (list.get(i-1).compareTo(list.get(i)) != 1) sorted = false;
    }

    return sorted;
}

Easy test:

简单测试:

    ArrayList<String> animals = new ArrayList<String>();
    ArrayListMethods zoo = new ArrayListMethods(animals); 
    animals.add("ape");
    animals.add("dog");
    animals.add("zebra");

    //test isSorted
    System.out.println(zoo.isSorted());
    System.out.println("Expected: true");

    animals.add("cat");
    System.out.println(zoo.isSorted());
    System.out.println("Expected: false");

    animals.remove("cat");
    animals.add(0,"cat");
    System.out.println(zoo.isSorted());
    System.out.println("Expected: false");

    **Output:**
    false
    Expected: true
    false
    Expected: false
    false
    Expected: false

This easy test shows only 1/3coverage.

这个简单的测试只显示1/3覆盖率。

How to solve this issue.

如何解决这个问题。

回答by Grisha Weintraub

You have a small bug in your method. Should be :

你的方法有一个小错误。应该 :

public boolean isSorted()
{
    boolean sorted = true;        
    for (int i = 1; i < list.size(); i++) {
        if (list.get(i-1).compareTo(list.get(i)) > 0) sorted = false;
    }

    return sorted;
}

>0instead of !=1, you can't be sure that 1is returned..

>0而不是!=1,你不能确定它1被退回了..

回答by NINCOMPOOP

Change the condition :

改变条件:

if (list.get(i - 1).compareTo(list.get(i)) >0)

You should check for >0instead of !=-1.

您应该检查 for>0而不是!=-1

Go through the documentation of compareTo()

查看compareTo()的文档

the value 0 if the argument string is equal to this string; a value less than 0 if this string is lexicographically less than the string argument; and a value greater than 0 if this string is lexicographically greater than the string argument.

如果参数字符串等于此字符串,则值为 0;如果此字符串按字典顺序小于字符串参数,则为小于 0 的值;和的值大于0,如果该字符串是字典顺序比字符串参数越大。

回答by Ruchira Gayan Ranaweera

Try this

试试这个

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Sort {
public static void main(String []args) {
    List<String> l1=new ArrayList<String>();
    List<String> l2=new ArrayList<String>();
    l1.add("a");
    l1.add("b");
    l1.add("c");

    l2.add("b");
    l2.add("c");
    l2.add("a");

     if(isSorted(l1)){
         System.out.println("already sorted");
     }
    else{
         Collections.sort(l1);
     }
   }
public static boolean isSorted(List<String> list){
    String previous = "";
    for (String current: list) {
        if (current.compareTo(previous) < 0)
            return false;
        previous = current;
    }
    return true;
}
}

回答by prasanth

You can write a utily method like isSortedList(List list).

您可以编写一个实用的方法,例如isSortedList(List list).

public static boolean isSortedList(List<? extends Comparable> list)
{
    if(list == null || list.isEmpty())
        return false;

    if(list.size() == 1)  
        return true;

    for(int i=1; i<list.size();i++)
    {
        if(list.get(i).compareTo(list.get(i-1)) < 0 )
            return false;
    }

    return true;    
}

As as utility method, you can use it anywhere.

作为实用方法,您可以在任何地方使用它。

回答by Isaac.Lopez

you have to change the compareTo expresion to any positive number, which indicates that the previous element is alphabetically after the current element, hence the list is not ordered

您必须将 compareTo 表达式更改为任何正数,这表示前一个元素按字母顺序在当前元素之后,因此列表未排序

    public boolean isSorted()
    {
        boolean sorted = true;        
        for (int i = 1; i < list.size(); i++) {
            if (list.get(i-1).compareTo(list.get(i)) > 0) sorted = false;
        }

        return sorted;
    }

回答by Saher Ahwal

You need to check for unsorted case.

您需要检查未分类的情况。

This means that if you are assuming sorting ascending, the unsorted case will be finding an element at index ibeing out of order from index i-1where element[i] < element[i-1].

这意味着,如果您假设升序排序,则未排序的情况将发现 index 处的元素i与 index i-1where的顺序不一致element[i] < element[i-1]