我目前在java编码频率分类器,但是无法实现正确的输出。输出应该在其频率旁边具有正确的字符,而不是字符不按频率排序。频率的输出是正确的,但字符不是。我不确定如何更改或优化我的代码。我无法使用任何java分拣机进行此分配。使用的示例输入是AAAAbbbbccdd 42424242 &&%%$#@
,它应该输出
2 freq: 4
4 freq: 4
A freq: 4
b freq: 4
freq: 2
% freq: 2
& freq: 2
c freq: 2
d freq: 2
# freq: 1
$ freq: 1
@ freq: 1
public class Main {
public static void frequencySort(char[] beta) {
int size = beta.length;
int cnt;
int l = 0;
int cnttwo = 0;
int temp = 0;
int hold = 0;
char tempChar;
char holdChar;
char charlie[] = new char[256];
int countArray[] = new int[256];
int sortedArray[] = new int[256];
char charSorted[] = new char[256];
char delta[] = new char[256];
//assign beta array to charlie.
for (int i = 0; i < size; i++) {
charlie[i] = beta[i];
}
// this loop will count frequencies and store them in countArray and it
//will store the characters in charlie.
for (int i = 0; i < size; i++) {
cnt = 0;
for (int j = 0; j < size; j++) {
if (j < i && charlie[i] == charlie[j]) {
break;
}
if (charlie[j] == charlie[i]) {
cnt++;
}
if (j == size - 1) {
countArray[i] = cnt;
delta[i] = charlie[i];
}
}
}
for( int i=0; i<countArray.length; i++ )
{
if (countArray[i] != 0)
countArray[l++] = countArray[i];
}
//Here i copied the countArray to the newArray and removed the zeros
from the
//original countArray.
int [] newArray = new int[256];
System.arraycopy( countArray, 0, newArray, 0, l );
size = newArray.length;
for (int i = 0; i < size; i++)
{
sortedArray[i] = 0;
charSorted[i] = '\0';
}
for (int j = 0; j<size; j++)
{
temp = 0;
tempChar = '\0';
for (int i = 0; i < size; i++)
{
if (newArray[i] > temp)
{
temp = newArray[i];
tempChar = delta[i];
hold = i;
}
}
sortedArray[j] = temp;
charSorted[j] = tempChar;
newArray[hold] = 0;
}
for (int i = 0; i < l; i++) {
System.out.println(charSorted[i] + " " + sortedArray[i]);
}
}
public static void main (String[]args){
Scanner scanner = new Scanner(System.in);
System.out.println("Welcome to Character Sorter Program");
System.out.println("Please input a string to be sorted");
String orig = scanner.nextLine(); // User input of string
char[] charArray = orig.toCharArray(); // convert the original
string to a char array
frequencySort(charArray);
}
}