Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
559 views
in Technique[技术] by (71.8m points)

Faster way to sort an array of structs c++

I have a struct called count declared called count with two things in it, an int called frequency and a string called word. To simplify, my program takes in a book as a text file and I count how many times each word appears. I have an array of structs and I have my program to where it will count each time a word appears and now I want a faster way to sort the array by top frequency than the way I have below. I used the bubble sorting algorithm below but it is taking my code way too long to run using this method. Any other suggestions or help would be welcome!! I have looked up sort from the algorithm library but don't understand how I would use it here. I am new to c++ so lots of explanation on how to use sort would help a lot.

void sortArray(struct count array[],int size)
{
    int cur_pos = 0;
    string the_word;
    bool flag= true;

    for(int i=0; i<(size); i++)
    {
        flag = false;
        for(int j=0; j< (size); j++)
        {
            if((array[j+1].frequency)>(array[j].frequency))
            {
                cur_pos = array[j].frequency;
                the_word = array[j].word;
                array[j].frequency = array[j+1].frequency;
                array[j].word = array[j+1].word;
                array[j+1].frequency = cur_pos;
                array[j+1].word = the_word;
                flag = true;
            }
        }
    }
};
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You just need to define operator less for your structures, and use std::sort, see example:

http://en.wikipedia.org/wiki/Sort_%28C%2B%2B%29


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...