Question: Im currently coding a frequency sorter in java and am having trouble achieving the correct output. The output should have the correct character next to
Im currently coding a frequency sorter in java and am having trouble achieving the correct output. The output should have the correct character next to its frequency but instead the characters are not sorting with the frequency. The output of the frequencies is correct but the characters are not. Im not sure how I can change this or optimize my code.
import java.util.Scanner; 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; iarraycopy( 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 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); } }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
