0% found this document useful (0 votes)
6 views1 page

Java CharFrequencyArray

The document contains a Java program that calculates the frequency of characters in a given string and prints them in order of frequency. It uses arrays to store character frequencies, their first occurrence indices, and a boolean array to track seen characters. The output displays each character alongside its frequency, sorted primarily by frequency and secondarily by the order of first appearance.

Uploaded by

maniish6385
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views1 page

Java CharFrequencyArray

The document contains a Java program that calculates the frequency of characters in a given string and prints them in order of frequency. It uses arrays to store character frequencies, their first occurrence indices, and a boolean array to track seen characters. The output displays each character alongside its frequency, sorted primarily by frequency and secondarily by the order of first appearance.

Uploaded by

maniish6385
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

public class CharFrequencyArray {

public static void main(String[] args) {


String str = "abcabcca";
int[] freq = new int[256];
int[] firstIndex = new int[256];
boolean[] seen = new boolean[256];
char[] chars = new char[256];
int count = 0;

for (int i = 0; i < 256; i++) {


firstIndex[i] = -1;
}

for (int i = 0; i < str.length(); i++) {


char ch = str.charAt(i);
freq[ch]++;
if (firstIndex[ch] == -1) {
firstIndex[ch] = i;
}
if (!seen[ch]) {
chars[count++] = ch;
seen[ch] = true;
}
}

for (int i = 0; i < count - 1; i++) {


for (int j = i + 1; j < count; j++) {
char a = chars[i];
char b = chars[j];

if (freq[b] > freq[a] ||


(freq[b] == freq[a] && firstIndex[b] < firstIndex[a])) {
char temp = chars[i];
chars[i] = chars[j];
chars[j] = temp;
}
}
}

for (int i = 0; i < count; i++) {


char ch = chars[i];
System.out.println(ch + "----" + freq[ch]);
}
}
}

You might also like