[英]How can i sort a string without using sort() method in java?
I want to sort a string "computer" -> "cemoprtu", but without using Arrays.sort(string).我想对字符串“计算机”->“cemoprtu”进行排序,但不使用 Arrays.sort(string)。
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
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);
}
}
}
查看不同的排序算法并实现一些,尝试冒泡然后快速排序。
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]); } } }
class Abc { 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 = i+1; 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]);
}
}
} }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.