首页 > 解决方案 > 在 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 的文本文件,该文件按以下顺序包含以下名称

  1. 塞缪尔说
  2. 路易丝·斯蒂芬
  3. 斯蒂芬韦克菲尔德
  4. 帕蒂·安德森
  5. 约翰胡佛

当我运行选择排序时,我会按此顺序返回此序列。

  1. 路易丝·斯蒂芬
  2. 约翰胡佛
  3. 帕蒂·安德森
  4. 塞缪尔说
  5. 斯蒂芬韦克菲尔德

据我对 ASCII 的了解,这些不是正确的值。请告知。

标签: c++algorithmsorting

解决方案


你增加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++;行。


推荐阅读