123
123

Reputation: 8951

Sort strings using selection sort

I'm trying to create a function that sorts strings, and I've made a function that I think should work, but the toupper() function doesn't seem to be having any effect. Is there something I am missing here?

void selectionSort(string array[], int size) {
    int startScan, minIndex;
    string minValue;

    for(startScan=0; startScan<(size-1); startScan++) {
        minIndex = startScan;
        minValue = array[startScan];

        for(int index=startScan+1; index<size; index++) {
            string word = array[index];
            toupper(word[0]);
            if(array[index] < minValue) {
                minValue = array[index];
                minIndex = index;
            }
        }
        array[minIndex] = array[startScan];
        array[startScan] = minValue;
    }
}

Upvotes: 1

Views: 456

Answers (2)

Constantin
Constantin

Reputation: 8961

You're not assigning the return value of the toupper() function. But anyway, it doesn't do, what you probably think it does (regardless, that word is not used afterwards): It will just capital one letter. What you probably want to do is to capitalize the whole word:

std::transform with toupper as a parameter can be used.

#include <string>
#include <algorithm>
void selectionSort(string array[], int size) {
  int startScan, minIndex;
  string minValue;

  for (startScan = 0; startScan<(size - 1); startScan++) {
    minIndex = startScan;
    minValue = array[startScan];

    for (int index = startScan + 1; index<size; index++) {
      string word = array[index];
      std::transform(word.begin(), word.end(), word.begin(), ::toupper);
      if (array[index] < minValue) {
        minValue = array[index];
        minIndex = index;
      }
    }
    array[minIndex] = array[startScan];
    array[startScan] = minValue;
  }
}

Upvotes: 2

Yu Hao
Yu Hao

Reputation: 122383

toupper(word[0]);

This statement calculates the value of the expression toupper(word[0]), and then throws the result away.

Change it to:

word[0] = toupper(word[0])

Upvotes: 3

Related Questions