c++ - 随机字符串数组的选择排序
问题描述
我正在尝试创建一个选择排序算法,该算法接受一组随机字符串并对其进行排序。我已经在网上和我的书中查看过,试图用它来模拟我的代码,这就是我想出的。我不确定我哪里出错了,任何帮助将不胜感激。
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]);
}
}
推荐阅读
- android - Gradle 在从网络下载工件时抛出错误
- c - MergeSort 函数中的不良行为
- python - 在相同的布局中使用 serialize() 打印 rdflib.Graph
- oracle11g - 无法删除表 Oracle
- assembly - MPLABX 5.40 MPASM 汇编 PIC
- linux - 在 Docker 中不断重启容器
- google-sheets - 如何每 x 行重复一个表 - 谷歌表
- ios - 带有 Woocommerce 的 FlexSlider:防止水平滑块上的垂直滑动触摸
- node.js - SyntaxError:在 Docker 容器上部署 React 应用程序时出现意外标识符
- php - 传递给方法后的PHP Laravel数组空值