Search code examples
c++sortingvectorselection-sort

How to sort a vector<string> using selection sort


If a string vector std::vector<string> v, exists, using STL, we can sort like this:

std::sort(v.begin(), v.end());

I want to do this using selection sort, and here is my pseudocode:

//for(i=0 to n-1){
//int min = i;
//for (j = i+1 to n){
//if (array[j]<array[min]){
//min = j;
//}
//if (min != i){
//swap array[min] and array[i];
//}
//}
//}

My following implementation using iterators does not sort properly:

void sortDictionaryInsertionSort(){

        //for(i=0 to n-1)
        for (vector<string>::iterator oit = v.begin(); oit != v.end() - 1; oit++){
            //int min = i;
            vector<string>::iterator min = oit;
            //for j = i+1 to n
            for (vector<string>::iterator iit = v.begin() + 1; iit != v.end(); iit++){
                //if array[j]<array[min]
                if (iit->compare(*min) < 0){
                    //min = j;
                    min = iit;
                }
            }
            //if (min != i){
            if (min != oit){
                //swap array[min] and array[i]
                std::iter_swap(min, oit);
            }
        }

    }

so if the vector contains:

fezzy
dizzy
abuzz

after sorted, it should look like this:

abuzz
dizzy
fezzy

Solution

  • You should be initializing itt to iterate only over the unsorted range after oit, not the whole vector from the beginning (that will mix up already sorted elements again):

    vector<string>::iterator iit = oit + 1;
    

    And you should check if(v.empty()) return; at the beginning of the function. Doing
    v.end() - 1 on an empty container is undefined behavior.