c++ - 在 C++ 中对字符串数组使用选择排序
问题描述
我在此选择排序上产生正确结果时遇到问题。我觉得好像代码是正确的并且逻辑有效,但就我目前的理解而言,我得到的结果是不正确的。这是我的代码:
#include "stdafx.h"
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
using namespace std;
// Function prototypes
void selectionSort(string[], int);
string linearSearch(string[]);
// Declare variables
const int MAX_FRIENDS = 250;
int currentIteration = 0;
主要的:
int main()
{
// Declare stream file
fstream names;
names.open("myFriends.txt");
string friends[MAX_FRIENDS];
while(getline(names,friends[currentIteration])){
currentIteration++;
}
cout << "Before Sort:\n\n";
for(int i = 0; i < currentIteration; i++){
cout << "Index " << i << ": " << friends[i] << endl;
}
selectionSort(friends,5);
cout << "\nAfter Sort: \n\n";
for(int i = 0; i < currentIteration; i++){
cout << "Index " << i << ": " << friends[i] << endl;
}
system("pause");
return 0;
}
函数声明
void selectionSort(string arr[], int num){
// Declare Necessary Variables
int startScan,minIndex, index;
string minValue;
for(startScan = 0; startScan < (num - 1); startScan++){
index = startScan;
minIndex = startScan;
minValue = arr[startScan];
for(index = (startScan + 1); index < num; index++){
if(arr[index] < minValue){
minValue = arr[index];
minIndex = index;
}
index++;
}
arr[minIndex] = arr[startScan];
arr[startScan] = minValue;
}
}
我正在使用 myFriends 的文本文件,该文件按以下顺序包含以下名称
- 塞缪尔说
- 路易丝·斯蒂芬
- 斯蒂芬韦克菲尔德
- 帕蒂·安德森
- 约翰胡佛
当我运行选择排序时,我会按此顺序返回此序列。
- 路易丝·斯蒂芬
- 约翰胡佛
- 帕蒂·安德森
- 塞缪尔说
- 斯蒂芬韦克菲尔德
据我对 ASCII 的了解,这些不是正确的值。请告知。
解决方案
你增加index
了两次。
for(index = (startScan + 1); index < num; index++){ // increment it here
if(arr[index] < minValue){
minValue = arr[index];
minIndex = index;
}
index++; // and increment it also here
}
所以你只检查数组的所有其他元素。
摆脱第二index++;
行。
推荐阅读
- python - 在 jupyter 中读取 csv 文件时出现错误
- chatterbot - 在运行 chatterbot 之前我还错过了另一个库吗?
- npm - 什么是 npm create 命令?
- c++ - 无法推断“节点”的模板参数
*' 来自 'int' - jquery - 如何将数据写入数组Jquery?
- python - 如何正确处理此读取超时错误?
- java - 如何在 Java FX 应用程序中执行外部调用以构建和运行 arduino 程序?
- php - PHP Canvas 无法显示
- javascript - 使用 moment.js 倒计时到特定的日期和时间
- javascript - 如何从内容可编辑的 div 复制内文?