字符串排序先导 键索引计数法 (c++ )

对test.txt 按组号进行排序
稳定性不变是该方法能应用于字符串排序的决定性因素

Anderson 2
Brown 3
Davis 3
Carcia 4
Harris 1
Jackson 3
Johnson 4
Jones 3
Martin 1
Martinez 2
Miller 2
Moore 1
Robinson 2
Smith 4
Taylor 3
Thomas 4
Thompson 4
White 2
Williams 3
Wilson 4

Group.h

#pragma once
#include 

class Group
{
private:
    int gnum;
    std::string s;
public:
    Group(const int& i, const std::string& s) :gnum(i), s(s)
    {

    }
    Group() 
    {

    }
    Group(const Group& g):gnum(g.gnum),s(g.s)
    {

    }
    Group& operator = (const Group& g)
    {
        gnum = g.gnum;
        s = g.s;
        return *this;
    }
    int group_number()const
    {
        return gnum;
    }
    std::string person_name()const
    {
        return s;
    }
};

GroupSort.h 键索引计数法核心操作

#pragma once
#include "Group.h"
#include 

class GroupSort
{
private:
    Group* gp;
    std::unique_ptr<int[]> count;
    int size;
    int mg;
    std::unique_ptr ectype;
    void stat_count()
    {
        for (int i = 0; i < size; ++i)
            count[gp[i].group_number() + 1]++;
        for (int i = 0; i < mg - 1; ++i)
            count[i + 1] += count[i];
        for (int i = 0; i < size; ++i)
            gp[count[ectype[i].group_number()]++] = ectype[i];
    }
public:
    GroupSort(Group g[],const int& n,const int& mc):gp(g),count(new int[mc + 1]),size(n),mg(mc + 1),ectype(new Group[n])
    {
        for (int i = 0; i < mc; ++i)
            count[i] = 0;
        for (int i = 0; i < n; ++i)
            ectype[i] = g[i];
        stat_count();
    }
};

main.cpp

#include 
#include "Group.h"
#include 
#include "GroupSort.h"

using namespace std;

void read_Group(Group *g,const string& file)
{
    ifstream in(file);
    int i = 0;
    while (!in.eof())
    {
        int gnum;
        string s;
        in >> s >> gnum;
        g[i] = Group(gnum, s);
        ++i;
    }
}

int main()
{ 
    Group g[20];
    read_Group(g, "test.txt");
    GroupSort gs(g, 20, 5);
    for (int i = 0; i < 20; ++i)
        cout << g[i].person_name() << ends << g[i].group_number() << endl;
    system("pause");
    return 0;
}

运行:

字符串排序先导 键索引计数法 (c++ )_第1张图片

你可能感兴趣的:(算法)