java - 按字母顺序排列字符串(不使用compareTo方法)

标签 java string sorting while-loop compareto

我尝试在不使用 compareTo() 的情况下对字符串数组进行排序,但我陷入了 while 循环中。有没有一种方法可以在不使用 compareTo()Arrays.sort() 的情况下按字母顺序对字符串进行排序?

public class mycode 
{

    public static void main(String[ ] args)
    {
            String[ ] ar = {"hello", "java", "elephant", "array"};
            mycode.display(ar);
            mycode.bubbleSort(ar);
            mycode.display(ar);
    }
    static void display(String[] ar)
    {
        System.out.println("***********************");
        for(int i = 0; i < ar.length; i++)
        {
            System.out.println(ar[i]);
        }
        System.out.println("***********************");

    }
    static void bubbleSort(String[] ar)
    {
        int theFollower;
        for(int currStart = 1; currStart < ar.length; currStart++)
        {
            theFollower = currStart;
            while(theFollower != 0 && ar[theFollower] < ar[theFollower - 1]) //this is where my problem is
            {
                String swap = ar[theFollower];
                ar[theFollower] = ar[theFollower - 1];
                ar[theFollower - 1] = swap;
                theFollower--;
            }
        }
    }

}

按字母顺序排列是我的目标,所以我的输出如下

***********************
hello
java
elephant
array
***********************
***********************
array
elephant
hello
java
***********************

我使用建议的想法添加了这个方法,但我不确定我会放置什么来运行字符串的索引

    int alphabetize(String a, String b)
    {
    String A = a.toLowerCase();
    String B = b.toLowerCase();
    if (A < B)
    {
        return -1;
    }
    else if (A > B)
    {
        return  1;
    }
    else
    {
    }
    }

最佳答案

我假设这是作业,因为显而易见的方法就是使用 compareTo() ,所以我将提示您如何编写自己的方法来进行比较。您想要带有签名的东西

int compareStrings(String s, String t);

返回 -101取决于是否s按字母顺序位于 t 之前、等于或之后在字母表中。

浏览两个String s 逐个字符,并且在每个阶段,如果字符来自 s小于 t (这里你可以使用 < )然后返回 -1 ;如果更大,则返回 1 ;如果它们相等,则继续。

如果 s 中的字符用完但仍然有一些在 t ,然后返回-1 ,如果是相反则返回 1 。如果同时用完两者,请返回 0 .

关于java - 按字母顺序排列字符串(不使用compareTo方法),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26789205/

相关文章:

c - 使用 strtok() 的正确方法;

java - 在 Google App Engine 中创建实体

关于使用 Java 14 生成的 .class 的 Java 问题

java - For循环乘数

java - 事务需要异常 JPA/Spring

javascript - 如何使用Javascript计算数组中的相邻数字?

java - 如何替换字符串中的 ⁠(断线)?

java - 将字符串放入字节数组

c# - 如何对 List<T> 进行排序?

javascript - 使用方法 sort() 对数组元素中的符号进行排序