#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef
struct
{
int
first;
char
second;
} ppi;
bool
compare(ppi below, ppi above)
{
if
(below.first == above.first) {
return
below.second > above.second;
}
return
below.first > above.first;
}
char
* frequencySort(
char
* s)
{
int
i;
int
n =
strlen
(s);
char
* ans = (
char
*)
malloc
(
sizeof
(
char
) * (n + 1));
memset
(ans,
'\0'
,
sizeof
(
char
) * (n + 1));
int
* mpp = (
int
*)
calloc
(
sizeof
(
int
), 256);
ppi* arr = (ppi*)
malloc
(
sizeof
(ppi) * 256);
int
k = 0;
for
(i = 0; i < n; i++) {
mpp[s[i]]++;
}
for
(i = 0; i < 256; i++) {
if
(mpp[i]) {
arr[k].first = mpp[i];
arr[k].second = i;
k++;
}
}
ppi* heap = (ppi*)
malloc
(
sizeof
(ppi) * k);
for
(i = 0; i < k; i++) {
heap[i] = arr[i];
}
int
heapSize = k;
for
(i = heapSize / 2; i >= 0; i--) {
int
parent = i;
int
child = 2 * parent + 1;
while
(child < heapSize) {
if
(child + 1 < heapSize
&& compare(heap[child], heap[child + 1])) {
child++;
}
if
(compare(heap[parent], heap[child])) {
ppi temp = heap[parent];
heap[parent] = heap[child];
heap[child] = temp;
parent = child;
child = 2 * parent + 1;
}
else
{
break
;
}
}
}
while
(heapSize > 0) {
ppi top = heap[0];
for
(i = 0; i < top.first; i++) {
ans[
strlen
(ans)] = top.second;
}
heap[0] = heap[heapSize - 1];
heapSize--;
int
parent = 0;
int
child = 2 * parent + 1;
while
(child < heapSize) {
if
(child + 1 < heapSize
&& compare(heap[child], heap[child + 1])) {
child++;
}
if
(compare(heap[parent], heap[child])) {
ppi temp = heap[parent];
heap[parent] = heap[child];
heap[child] = temp;
parent = child;
child = 2 * parent + 1;
}
else
{
break
;
}
}
}
free
(arr);
free
(heap);
free
(mpp);
return
ans;
}
int
main()
{
char
str[] =
"geeksforgeeks"
;
printf
(
"%s\n"
, frequencySort(str));
return
0;
}