Sorting characters within a string
I'm trying to sort characters alphabetically in String, and when I run my code in the following example:, hello
I get: heeeeeeeeeheeeelheeellhee
instead ehllo
. Can smb suggest me what should I fix in my code? Thanks in advance!
public static void main(String[] args)
{
String result = "";
Scanner kbd = new Scanner(System.in);
String input = kbd.nextLine();
char[] myArray = input.toCharArray();
for(int i = 0; i < myArray.length; i++)
for(int j = 0; j < myArray.length; j++)
{
if(myArray[i] > myArray[j])
{
char temp = myArray[j];
myArray[j] = myArray[i];
myArray[i] = temp;
result += myArray[i];
}
else
result += myArray[i];
}
System.out.println(result);
}
At each iteration of your loop, you add a character in i
to the array before result
, but the array is not sorted yet
The loop will run for loops n * (n - 1)
, so for String
5 characters it will be 5 * (5 - 1)
(or 20) iterations.
Instead, sort the array and then create a new String
one based on its contents ...
String input = "hello";
char[] myArray = input.toCharArray();
for (int i = 0; i < myArray.length; i++) {
for (int j = 1; j < myArray.length; j++) {
if (myArray[i] > myArray[j]) {
char temp = myArray[j];
myArray[j] = myArray[i];
myArray[i] = temp;
}
}
}
System.out.println(new String(myArray));
Also note: for (int j = 0; j < myArray.length; j++) {
Wrong and should be for (int j = 1; j < myArray.length; j++) {
, otherwise you will be comparing the same character at the same position, which you don't want to do ...
A more "accurate" bubble might look something like this ...
for (int i = 0; i < (myArray.length - 1); i++) {
for (int j = 0; j < myArray.length - i - 1; j++) {
if (myArray[j] > myArray[j + 1]) {
char swap = myArray[j];
myArray[j] = myArray[j + 1];
myArray[j + 1] = swap;
}
}
}
source to share