我想对字符串“computer”->“cemoprtu”进行排序,但不使用 Arrays.sort(string)。
看起来你需要对字符进行排序,所以我从
开始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 {
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]);
}
}
}
// Java program to sort
// a string of characters
public class SortString{
static final int MAX_CHAR = 26;
// function to print string in sorted order
static void sortString(String str) {
// Hash array to keep count of characters.
int letters[] = new int[MAX_CHAR];
// Traverse string and increment
// count of characters
for (char x : str.toCharArray()) {
// 'a'-'a' will be 0, 'b'-'a' will be 1,
// so for location of character in count
// array we will do str[i]-'a'.
letters[x - 'a']++;
}
// Traverse the hash array and print
// characters
for (int i = 0; i < MAX_CHAR; i++) {
for (int j = 0; j < letters[i]; j++) {
System.out.print((char) (i + 'a'));
}
}
}
// Driver program to test above function
public static void main(String[] args) {
sortString("eeffjaaannnfffnn");
}
}