c++ - 随机字符串数组的选择排序

标签 c++ algorithm visual-studio sorting selection-sort

我正在尝试创建一个选择排序算法,该算法接受一个随机字符串数组并对其进行排序。 我在网上和我的书中都看过,试图用它来模拟我的代码,这就是我想出的。我不确定哪里出错了,如有任何帮助,我们将不胜感激。

Here is how you load the array with the random strings:
string Sorter::randomString() {
    string s = "";
    for (int i = 0; i < MAX_CHARS; i++) {
        char randomChar = char(rand() % 26 + 97);
    s += randomChar;
    }
    return s;
}

void Sorter::load() {
    for (int i = 0; i < MAX_STRINGS; i++)
        workspace[i] = randomString();

Here is my selection sort: 

void Sorter::selectionSort() {
    for (int pass = 0; pass < MAX_STRINGS - 1; pass++) {
        string smallest = workspace[pass];
    for (int pos = pass + 1; pos < MAX_STRINGS - pass - 1; pos++) {
            if (workspace[pos] > smallest) {
                smallest = workspace[pos];
            }
            swap(workspace[pos], workspace[pass]);
        }
    }
}

我希望对数组工作区进行排序,但事实并非如此:(

最佳答案

您的逻辑存在一些缺陷,因为您没有正确设置列表中的最小元素。您应该为此使用最小索引。

void selectionSort() {
    //Initialise minimum index
    int min_id = 0;
    //Loop through unsorted subarray 
    for (int pass = 0; pass < MAX_STRINGS - 1; pass++) {
        //Find the minimum element in rest of array
        min_id = pass;
        for (int pos = pass + 1; pos < MAX_STRINGS; pos++) {
            if (workspace[pos] < workspace[min_id]) {
                min_id = pos;
            }
        }
        //Swap the minimum element with current element in array
        swap(workspace[min_id], workspace[pass]);
    }
}

关于c++ - 随机字符串数组的选择排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58583125/

相关文章:

algorithm - 求除法 float 倒数的牛顿法

algorithm - 给定两棵二叉树,计算它们的差异

c# - 将 Visual Studio 2005 (C#) 连接到 Oracle8 最方便的方法是什么?

visual-studio - 如何使用从 Paket 下载的依赖项构建 F# 应用程序?

c++ - 如何专门化模板类成员函数?

c++ - 如何在 OSX 中创建可动态加载的 RtAudio 版本

python - 算法:如何删除所有其他文件

c# - 未定义的预处理器变量 '$(var.WixInstall.TargetPath)' 。 WixInstaller D :work\Extractor\WixInstaller\Product. wxs

c++ - 无法理解 C 和 C++ 中缓冲区大小的不同实验结果。 ifstream 也比 FILE 慢吗?

c++ bmp to 2d-array 打印不切实际的值