Question

I am trying to put the empty (example[0] == '\0') c-strings in the back of the array instead of the front while keeping the sort order ascending. I am using strcmp(...) to compare the current cstring to the next cstring in the array using a simple selection sort, but would like to be able to apply this to other types of sorts as well

edit-- tempword is actually an object instead of a char* in my code, but this should be functionally equivalent

sortList() {
   char *tempword = new char[30];
   int min;

   for (int i=0; i<(d_length-1); ++i) {
      min = i;

      for (int j=i+1; j<d_length; ++j) {

         if ((strcmp(d_wordlist[min], d_wordlist[j]) > 0)) {
         min = j;
         }
      }

      if (min != i) {

         *tempword = d_wordlist[min];

         d_wordlist[min] = d_wordlist[i];

         d_wordlist[i] = *tempword;
      }
   }
   delete[] tempword;
}

*edit 2-- I ended up making a wrapper function for strcmp as suggested by "im so confused".

int compare(const char* str1, const char* str2) {
   if (str2[0] == '\0')
      return -1;
   return strcmp(str1, str2);
}
Was it helpful?

Solution

The straight-forward approach is to have your sortList function take a custom comparison function. Your custom comparison function should return false if the left operand is an empty string "". If the left operand is not empty but the right operand is empty than return true. Otherwise just do a regular string comparison.

For example, using std::string this comparison function should do the trick:

bool comp(const std::string &lhs, const std::string &rhs)
{
  if (lhs == "") return false;
  return rhs == "" || !(rhs < lhs);
}

Note that you'll need to fix your sortList to swap words instead of letters to get what you're looking for.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top