Tags
3-Way Quick Sort, Algorithms, Arrays, Frequency Distribution, Number of occurrence of each elements, Sorting
//C- Programm to find the frequency of the elements in an integer array (Using 3-Way Quicksort to sort Input array)
#include <stdio.h>
void quickSort(int a[],int low, int high); void partition(int a[],int low, int high, int *i, int *j); void swap(int *a,int *b); void printArry(int a[],int size);
int main(){ int a[] = {4, 9, 4, 4, 1, 9, 4, 4, 9, 4, 4, 1, 4};
int size = sizeof(a) / sizeof(int); printf("Input array: "); printArry(a,size); // To Print the Given array quickSort(a, 0, size - 1); //To sort teh given array of elements printf("Sorted array: "); printArry(a,size); // To Print the Sorted array
printf("----:Frequency Distribution of array elements:----\n"); int count = 0; int num = a[0]; int i; for (i = 0; i <= size; i++) { if (num != a[i]) { printf("\tElement %d occurs %d times.\n",num,count); num = a[i]; count = 0; i--; }else { count++; } } return 0; }
//Utility function to swap two numbers
void swap(int *a,int *b){
int temp = *a; *a = *b; *b = temp;
}
//To partition the given array
void partition(int a[],int low, int high, int *i, int *j){
if ((high-low) <= 1) { if (a[high] < a[low]) { swap(&a[high], &a[low]); *i = low; *j = high; return; } }
int mid = low; int pivot = a[high];
while (mid <= high) { if (a[mid] < pivot) { swap(&a[low++], &a[mid++]); } else if (a[mid] == pivot){ mid++; } else if (a[mid] > pivot){ swap(&a[mid], &a[high--]); } }
*i = low - 1; *j = mid;
}
//Implementation of quick sort recursively
void quickSort(int a[],int low, int high){
if (low >= high) { return; }
int i,j;
partition(a, low, high, &i, &j);
quickSort(a, low, i); quickSort(a, j, high);
}
//To print the array contents
void printArry(int a[],int size) { int i; for (i = 0; i < size; i++) { printf("\t%d",a[i]); } printf("\n"); }
SAMPLE INPUT/OUTPUT:
Input array: 4 9 4 4 1 9 4 4 9 4 4 1 4 Sorted array: 1 1 4 4 4 4 4 4 4 4 9 9 9 ----:Frequency Distribution of array elements:---- 1 occurs 2 times 4 occurs 8 times 9 occurs 3 times