sort on two keys, primary key is frequency, secondary key is
occurrence.
using namespace std;
struct Item{
int freq;
int occur;
char chr;
Item(){ freq = 0; occur = -1; chr = -1;};
};
bool sortItem(const Item a, const Item b){
if(a.freq != 0 && b.freq != 0){
if(a.freq != b.freq){
return a.freq > b.freq;
}else{
return a.occur < b.occur;
}
}else{
return b.freq < a.freq;
}
}
void sortBasedOnFreq(char *str){
Item *array = new Item[256];
for(int i = 0; str[i]!='\0'; i++){
int offset = str[i] + 128;
array[offset].freq++;
array[offset].chr = str[i];
if(array[offset].occur==-1){
array[offset].occur = i;
}
}
std::sort(array, array+256, sortItem);
for(int i = 0; i < 256; i++){
if(array[i].freq>0){
cout<<char(array[i].chr)<<" ";
}
}
cout<<endl;
}
On Jan 13, 1:23 am, Davin <[email protected]> wrote:
> Smaple Data :
>
> input : "abcdacdc"
> Output : "cadb"
>
> If the count is same for characters. maintain the original order of
> the characters from input string.
>
> Please do let me know for any clarification.
--
You received this message because you are subscribed to the Google Groups
"Algorithm Geeks" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/algogeeks?hl=en.