Building a database, trying to sort a 2D array alphabetically

Hey, I'm using a database and im trying to sort a 2D array info[51][10] that contains 51 pieces of records and 10 different fields for each record.
And, now I'm trying to sort a desired field in the 2D array alphabetically.
However, the other fields within the same record should be swapped together. (So that the information of the same records stays together).

Also, I am constantly experiencing a run-time error.
Sometimes my program works sometimes the whole thing crashes...
By opening the code in different folders sometimes works. But the problem is still here. Is there any way to fix this error?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
              

bool swapped =true;
int j=0;
string tmp[10];

                   
                        swapped =true;
                        j=0;
                        while(swapped){
                               swapped=false;
                               j++;
                               for (a=0;a<51;a++){
                                   if (info[a][1]>info[a+1][1]){
                                      for (int b=0;b<10;b++){
                                         tmp[b]=info[a][b];
                                         info[a][b]=info[a+1][b];
                                         info[a+1][b]=tmp[b];
                                      }
                                   }
                               }
                        }
                         for (int v=0;v<51;v++){
                            for (int g=0;g<10;g++){
                               cout<<info[v][g]<<endl;
                            }
                         }

Use structs to organise your data:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <algorithm>

struct RecordInfo
{
    std::string recordName;
    std::string artistName;
    /*...*/
};

//This is custom functor to use in std::sort, you can still sort manually
struct SortByName
{
    bool operator()(const RecordInfo& lhs, const RecordInfo& rhs)
    {
        return lhs.recordName < rhs.recordName;
    }
};

int main()
{
    RecordInfo info[51];
    //initialize your array here
    std::sort(info, info+51, SortByName()); //Sorting
    //Or use your sorting algorithm here.
    //You will have to only swap structs encapsulating all data in one piece
    //so you do not need to make sure that everything is swapped properly
}

Last edited on
Topic archived. No new replies allowed.