Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I need to implement a frequency array to sort through arrays of integers or char

ID: 3762385 • Letter: I

Question

I need to implement a frequency array to sort through arrays of integers or characters, can be sorted not by comparison but by distribution based on the value itself. Given an array of 200 numbers in the range 1-100, you will count the frequency of occurrence of each number and store these tallies in an array frequency. The array frequency will be of size 100 + 1, since index [0] will not be used if the numbers range from 1-100. A similar argument can be made for characters, since characters are integers internally (ASCII) and thus the usable range would then be [65]-[90]. Each index of the frequency array represents one of the 100 generated numbers, and the element itself represents that number's frequency. So, if index [4] has the value 5, it means that the number 4 occurred 5 times. Similarly if index [65] has the value 3, it means that the character 'A' occurred 3 times. To sort the array you then simply traverse the frequency array and display each index the designated number of times as given by its element's value. In the above reference, you would display the number 4, five times and the character 'A' 3 times.

I know that I need to typecast the characters into integers, and also use instanceOf.

Explanation / Answer

Answer:

import java.io.*;

import java.util.*;

public class HelloWorld

{

public static void freSort(Object[] obj)

{

Object o=new Object();

int[] numAry=new int[200];

int[] frqAry=new int[101];

if(o instanceof Character)

{

for(int k1=0;k1<200;k1++)

{  

numAry[k1]=(int)(obj[k1]);

}

}

else

for(int k1=0;k1<200;k1++)

{

numAry[k1]=(int)obj[k1];

}

//INITIALIZE THE FREQUENCY ARRAY

for(int k1=0;k1<101;k1++)

{

frqAry[k1]=0;

}

//COUNT THE FREQUENCY OF OCCURRENCES OF EACH ELEMENT

for(int k1=1;k1<=100;k1++)

{

for(int k2=0;k2<200;k2++)

{

if(numAry[k2]==k1)

frqAry[k1]++;

}

}

//FOR DISPLAYING THE CHARACTER

if(o instanceof Character)

{

//DISPLAY THE SORTED ARRAY

for(int k1=65;k1<=90;k1++)

{

   

for(int k2=1;k2<=frqAry[k1];k2++)

System.out.println((char)k1);

}

}

if(o instanceof Integer)

{

//DISPLAY THE SORTED ARRAY

for(int k1=1;k1<=100;k1++)

{

   

for(int k2=1;k2<=frqAry[k1];k2++)

System.out.println(k1);

}

}

for(int k1=1;k1<=100;k1++)

{

   

for(int k2=1;k2<=frqAry[k1];k2++)

System.out.println(k1);

}

}//END function   

//MAIN METHOD

     public static void main(String[] args)

{

Integer[] ex=new Integer[200];

Random r=new Random();

for(int k1=0;k1<200;k1++)

{

    ex[k1]=r.nextInt(100)+1;

}

freSort(ex);

}//END MAIN

}//END CLASS