如何在不使用 java 中的 sort() 方法的情况下对字符串进行排序?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5367469/
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-10-30 10:46:13  来源:igfitidea点击:

How can i sort a string without using sort() method in java?

javastringsorting

提问by hiren gamit

I want to sort a string "computer" -> "cemoprtu", but without using Arrays.sort(string).

我想对字符串“计算机”->“cemoprtu”进行排序,但不使用 Arrays.sort(string)。

回答by Thomas

Looks like you need to sort the characters, so I'd start with

看起来你需要对字符进行排序,所以我会从

String input = "computer";
char[] characters = input.toCharArray();
//now sort characters using some algorithm
String output = new String(sorted_characters); //sorted_characters might be characters after sorting, if you sort in place

回答by Sundar

package practice;


class Practice
{
public static void main(String args[])
{
   String s = "bcfaed";
   char a[]=s.toCharArray();
   char b[]=new char[a.length];
   int count=0;
   for(int i=0;i<a.length;i++)
   {
       count=0;
       for(int j=0;j<a.length;j++)
       {
       if(a[i]<a[j])
       {
       count++;
       }
       }
       b[count]=a[i];
   }
   for(char x:b)
   {
       System.out.println(x);
   }
}
}

回答by Morale Ashwini

class Abc {

    public static void main(String[] args) {
        String str = "welcome";
        char temp = 0;

        char arr[] = str.toCharArray();
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr.length; j++) {
                if (arr[j] > arr[i]) {
                    temp = arr[i];
                    arr[i] = arr[j];
                    arr[j] = temp;
                }
            }
        }

        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i]);
        }
    }
}

回答by Tom

Check out different sorting algorithmsand implement a couple, try bubble then quick sort.

查看不同的排序算法并实现一些,尝试冒泡然后快速排序。