I’m trying to write a code to actually sort my array in an ascending order, so what happen is that say this is what I have.
char myListArray[10][40];
myListArray = "Yeah?",
"Tomorrow",
"Again",
"I will see you";
So what happen is that it should be sort in the order by ASCII value.
Again
I will see you
Tomorrow
Yeah?
I’ve create something like this…
char temp[40];
temp[0] = '\0';
int i, j, pos = 10, flag = 1;
for(i = 1; (i <= pos) && flag; i++)
{
flag = 0;
for (j=0; j < (pos -1); j++)
{
if (phrase[i][j+1] > phrase[i][j])
{
strcpy(temp, phrase[i]);
strcpy(phrase[i], phrase[i+1]);
strcpy(phrase[i+1], temp);
flag = 1;
}
}
}
Now I don’t know I have a problem with my logic, and I wish to know if there is a function to sort easy way? or bubble sort is the easiest ?
UPDATE:
I will accept one of the answer below, but I have found my solution of how to sort my array in the easiest way.
while(pos < 9){
if(phrase[pos][i] > phrase[pos+1][i]){
strcpy(temp, phrase[pos]);
strcpy(phrase[pos], phrase[pos+1]);
strcpy(phrase[pos+1], temp);
flag = 1;
if(flag = 1){
pos = 0;
}
}
pos++;
}
Using
std::array,std::string, andstd::sort…This can also be trivially adapted to use C arrays or
std::vectorsif you don’t have access tostd::array.