简体   繁体   English

字符串选择排序C ++

[英]String Selection Sort C++

How would I modify a selectionSort function to search an array of strings? 如何修改selectionSort函数以搜索字符串数组?

void selectionSort (int array[], int size)
{
    int startScan, min Index, minValue;
    for (startScan = 0; startScan<(size-1); startScan++)
    {
        minIndex=startScan;
        minValue=array[startScan];
        for(int index = startScan + 1;index<size;index++)
        {
            if (array[index] < minValue)
            {
                minValue=array[index];
                minIndex=index;
            }
        }
    }
}

As I understand your question, you need to generalise ">" to strings -- you can obviously use some library function (for STL strings, > is defined), but if it is a homework, you are probably in need to write your own. 据我所知,您需要将“>”泛化为字符串-您显然可以使用某些库函数(对于STL字符串,定义为> ),但是如果这是一项家庭作业,则可能需要编写自己的函数。 If we are limited to ASCII, it is pretty straightforward while ASCII codes of letters hold alphabetical order ((int)'A'<(int)'B') . 如果我们仅限于ASCII,那么当字母的ASCII码保持字母顺序((int)'A'<(int)'B') ,这非常简单。
To compare strings, you should start with first letters of two strings, if they are not equal return the result of their comparison, and if they are the same proceed to the next pair. 要比较字符串,您应该以两个字符串的首字母开头,如果它们不相等,则返回比较结果;如果相同,则继续下一个对。

创建一个函子,该函子接受一个字符串数组并根据需要处理比较(如果是STL)。

The < and > operators are already able to handle comparing strings in alphabetical order. <和>运算符已经能够按字母顺序处理比较字符串。 just overload the function to have a string array [] instead of a int array [] in the parameters. 只是重载该函数,使其在参数中具有字符串数组[]而不是int数组[]。 The one problem is that these operators are case sensitive so you will need to convert all the characters in the string to upper or lower case before doing the check. 一个问题是这些运算符区分大小写,因此在进行检查之前,您需要将字符串中的所有字符转换为大写或小写。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM