Java-如何在不扩展比较器的情况下对包含句点/点的字符串数组进行排序?

时间:2017-06-18 16:39:13

标签: java arrays string sorting

Java noob在这里。我想对包含从最小到最大的句点/点的字符串数组进行排序。

所以包含:

的数组
1.0.3
1.0.12
1.0.2

错误地排序如下:

1.0.12
1.0.2
1.0.3

如果排序正确应为:

1.0.2
1.0.3
1.0.12

这是我到目前为止的代码,但它排序错误。

public static String[] sort(String[] l) {
        String[] ll=new String[l.length];
        for(int i=0;i<l.length;i++)
        {

        }

        for (int i = 0; i < l.length - 1; ++i) {
            int minIndex = i;
            for (int j = i + 1; j < l.length; ++j) {

                if (l[j].compareTo(l[minIndex]) < 0) {
                    minIndex = j;
                }
            }

            String temp = l[i];
            l[i] = l[minIndex];
            l[minIndex] = temp;


        }
        return l;


    }

3 个答案:

答案 0 :(得分:2)

编辑完整,可运行的版本。

使用类,可能更简单:

var stopwatch = new Stopwatch();
while (true)
{
    Console.WriteLine("Tap 'y' to start, 'n' to stop, or 'q' to quit.");
    switch (Console.ReadLine())
    {
        case "y":
            Console.WriteLine("start");
            // Resets *and* starts if necessary
            stopwatch.Restart();
            break;
        case "n":
            Console.WriteLine("stop");
            stopwatch.Stop();
            Console.WriteLine(stopWatch.Elapsed);
            break;
        case "q":
            return;
    }
}

执行追踪:

public class Version implements Comparable<Version> {

   public final int     major;
   public final Integer minor;
   public final Integer patch;

   public Version( String ver ) {
      final String[] parts = ver.split("\\.");
      this.major = Integer.parseInt( parts[0] );
      if( parts.length > 1 ) {
         this.minor = Integer.parseInt( parts[1] );
         if( parts.length > 2 ) {
            this.patch = Integer.parseInt( parts[2] );
         }
         else {
            this.patch = null;
         }
      }
      else {
         this.minor = null;
         this.patch = null;
      }
   }

   @Override
   public int compareTo( Version right ) {
      int diff = this.major - right.major;
      if( diff != 0 ) {
         return diff;
      }
      if( this.minor == null && right.minor == null ) {
         return 0;
      }
      if( this.minor == null && right.minor != null ) {
         return -1;
      }
      if( this.minor != null && right.minor == null ) {
         return +1;
      }
      diff = this.minor - right.minor;
      if( diff != 0 ) {
         return diff;
      }
      if( this.patch == null && right.patch == null ) {
         return 0;
      }
      if( this.patch == null && right.patch != null ) {
         return -1;
      }
      if( this.patch != null && right.patch == null ) {
         return +1;
      }
      diff = this.patch - right.patch;
      return diff;
   }

   @Override
   public String toString() {
      return String.format( "%d.%d.%d", major, minor, patch );
   }

   public static void main( String[] args ) {
      final List<Version> versions = new ArrayList<>( 20 );
      versions.add( new Version( "5.3" ));
      versions.add( new Version( "5.3.0" ));
      versions.add( new Version( "2.5" ));
      versions.add( new Version( "2.5.100" ));
      final Random r = new Random( System.currentTimeMillis());
      for( int i = 0; i < 20; ++i ) {
         final int maj = r.nextInt(  10 );
         final int min = r.nextInt(  10 );
         final int pat = r.nextInt( 100 );
         final Version v =
            new Version( String.format( "%d.%d.%d", maj, min, pat ));
         versions.add( v );
      }
      Collections.sort( versions );
      versions.forEach( System.err::println );
   }
}

答案 1 :(得分:-1)

您可以使用流来完成手头的任务。您可以在分隔符.上拆分字符串,然后将每个数字与其他数字进行比较,而不是仅仅比较它们的字符串;当我们发现两个或多个字符串之间的两个数字相等时,我们会使用.thenComparingInt来进一步比较。

String[] array = {"1.0.3" ,"1.0.12", "1.0.2"};
String[] result = Arrays.stream(array)
        .sorted(Comparator.comparingInt((String x) -> Integer.parseInt(x.split("\\.")[0]))
        .thenComparingInt((String x) -> Integer.parseInt(x.split("\\.")[1]))
        .thenComparingInt((String x) -> Integer.parseInt(x.split("\\.")[2]))).toArray(String[]::new);

结果数组包含:

[1.0.2, 1.0.3, 1.0.12]

答案 2 :(得分:-1)

也许这很难解析并转换为数字,但它解决了我们的问题。

public void test() {

    List<String> versions = new ArrayList<>(Arrays.asList(
            "1.0",
            "1.0.3",
            "1.1.131",
            "1.0.12",
            "1.0.2"
    ));
    List<String> expectedVersions = Arrays.asList(
            "1.0",
            "1.0.2",
            "1.0.3",
            "1.0.12",
            "1.1.131"
    );
    Comparator<String> versionComparator = new Comparator<String>() {

        @Override
        public int compare(String o1, String o2) {
            return parsedVersion(o1) - parsedVersion(o2);
        }

        private int parsedVersion(String version) {
            String cleared = version.replaceAll("\\.", "");
            return Integer.parseInt(cleared);
        }
    };
    versions.sort(versionComparator);
    System.out.println(versions.equals(expectedVersions));
}