Professional Documents
Culture Documents
*
* The only problem with this below process is if two elements has same count,
* then it doesn't preserve the order of those elements, the way they appeared.
* /
public class SortByFrequency {
int[] arr;
int[][] elements;
/*
* now we will create a 2-D array and store the elements in the first
* column and in the second column we store their repetition count.
* Store the first element of the sorted array in the
*/
int fIndex = 0;
elements[fIndex][0] = arr[0];
elements[fIndex][1] = 1;
/*
* Printing 2-D array after creating
*/
System.out.println("Printing 2-D array after creating:");
for (int i = 0; i <= fIndex; i++) {
for (int j = 0; j < 2; j++) {
System.out.print(elements[i][j] + " ");
}
System.out.println();
}
/*
* Now we need to sort this two dimensional array based on it's
* occurrence. Hence we need to write another sort method which will
* take a two dimensional array as input.
*/
sort(elements, fIndex);
/*
* Now we are done with sorting the 2-D array elements as well. Need to
* print the first column of the 2-D array. For every element we need to
* check it's corresponding repetition count in the second column &
* print accordingly.
*/
System.out.println();
for (int i = 0; i <= fIndex; i++) {
for (int j = 0; j < elements[i][1]; j++) {
System.out.print(elements[i][0] + " ");
}
}
}
/**
* Implementing bubble sort
* @param elements
* @param fIndex
* @return
*/
public int[][] sort(int elements[][], int fIndex) {
/*
* In a 2-D array, each row represents an array. Here in this case, we
* have a 2-D array with n rows and two columns.
*/
/**
* Implementing bubble sort
*
* @param arr
* @return
*/
public int[] sort(int[] arr) {
long startTime = System.nanoTime();
int passCounter;
for (int i = 0; i < arr.length; i++) {
passCounter = 0;
for (int j = 1; j < arr.length - i; j++) {
if (arr[j - 1] > arr[j]) {
passCounter++;
swap(j - 1, j);
}
}
System.out.println("For i = " + i + "--> passCounter value: "
+ passCounter);
if (passCounter == 0) {
System.out.println("Breaking the outer loop");
break;
}
}
long stopTime = System.nanoTime();
System.out.println(stopTime - startTime);
System.out.println();
return arr;
}