Steve Way
Steve Way

Reputation: 177

Sort algorithm to sort a list of strings (C#)

I'm doing this assignment for uni and the requirement is that I use any sorting algorithm to sort a List in alphabetical order (case insensitive). Basically say if the list contains some strings for example, "a" "C" "b" "1" and "3" it will sort it to either "1" "3" "a" "b" "C" or "a" "b" "C" "1" "3" I know how to sort an array of integers (code below using exchange sort) but how do I use a list of strings instead? How to modify the code below to sort a list of strings alphabetically while still maintaining the principles of exchange sort (in this case)?

Note: I am not allowed to use List<string>.Sort() or some other simple code.

        // sort a vector of type int using exchange sort
        public void ExchangeSort(int[] array)
        {
            int pass, i, n = array.Length;
            int temp;
            // make n-1 passes through the data 
            for (pass = 0; pass < n - 1; pass++)
            {
                // locate least of array[pass] ... array[n - 1]  
                // at array[pass] 
                for (i = pass + 1; i < n; i++)
                {
                    if (array[i] < array[pass])
                    {
                        temp = array[pass];
                        array[pass] = array[i];
                        array[i] = temp;
                    }
                }
            }
        }

Upvotes: 1

Views: 1723

Answers (1)

cHao
cHao

Reputation: 86506

You'll probably need to compare the strings char by char.

In pseudocode:

for each I from 0 to (shorter string's length - 1):
    if left[I] is a letter and right[I] isn't (or vice versa):
        the string that has a letter at [I] is "less"
        done
    else:
        ("true" here means ignore case)
        (you could also say `StringComparison.InvariantCultureIgnoreCase`, but eh)
        result = String.Compare(left, I, right[I], I, 1, true)
        if result < 0
            left is "less"
        else if result > 0
            right is "less"
        else
            (both strings are equal so far)
            next I

(if you're here, the strings are "equal" up to this point)

if both strings have the same length:
    they're equal
else:
    the longer string is "greater"

Upvotes: 3

Related Questions