ihoaxed
ihoaxed

Reputation: 137

How to rearrange characters in string?

Assume I have the following string:

String numbers = "01010101"

How can I arrange the characters in this string so that it prints out as following:

00001111

If someone can explain the concept behind this too that would be awesome.

Upvotes: 2

Views: 9073

Answers (2)

Khazam Alhamdan
Khazam Alhamdan

Reputation: 98

String numbers = "01010101"
char[] charNumbers = numbers.toCharArray();
char[] resultNumbers = new char[numbers.length];

char min = charNumbers[0];
int index = 0;
for(int j = 0 ;j=charNumbers.length;j++){
   for(int i = 0 ;i=charNumbers.length;i++){
      if(min<charNumbers[i]){
         index = i;
         min = charNumbers[i];
         }
      }
   resultNumbers[j]=min;
   charNumbers[index] = (char)255;
}

You can have two arrays of characters "charNumbers", and "resultNumbers", in which charNumbers contains the original string = "01010101" and the other one is empty.

Then we can loop on charNumbers array to search for the smallest character(or the smallest number), in each iteration(step in the loop) we check if the min is greater than the current character in the array or not, if it is greater than we pick the current character to be the min, and keep track of its index.

When we finish the inner loop, we got the min and its index, so we add that min to the resultNumbers array and remove the min from the charNumbers array by replacing it with (char)255, which is the biggest character possible. so in the next loop of searching for the next min we do not get fooled by the previous min.

Keep doing this algorithm, which will give you a sorted array if characters.

Upvotes: 1

Idos
Idos

Reputation: 15310

You can easily just convert the string to a char array and then sort it:

char[] arr = numbers.toCharArray(); // ['0','1','0','1','0','1','0','1']
Arrays.sort(arr); // ['0','0','0','0','1','1','1','1']
String sortedString = new String(arr); // "00001111"

Upvotes: 4

Related Questions