我的选择排序需要一些字符串帮助。这是我到目前为止所拥有的。
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
//Constant globals
const int NUM_NAMES = 20;
//Function protoypes
void selectionSort(string [], int);
void showArray(const string [] , int);
int main()
{
string names[NUM_NAMES] = {"Collins, Bill", "Smith, Bart", "Allet, Jim",
"Griffin, Jim", "Stamey, Marty", "Rose, Geri",
"Taylor, Terri", "Johnson, Jill",
"Aliison, Jeff", "Weaver, Jim", "Pore, Bob",
"Rutherford, Greg", "Javens, Renee",
"Harrison, Rose", "Setzer, Cathy",
"Pike, Gordon", "Holland, Beth"};
char again; //Hold y to repeat
do
{
//Show array
cout << "The unsorted values are\n";
showArray(names, NUM_NAMES);
//Sort array
selectionSort(names, NUM_NAMES);
//Display sorted array
cout << "The sorted values are\n";
showArray(names, NUM_NAMES);
//Run program again?
cout << "Would you like to run the program again? (Y/N): ";
cin >> again;
}while(again == 'y' || again == 'Y');
return 0;
}
更新了我的代码,它完美无缺。将minValue从int更改为string。
void selectionSort(string array[], int NUM_NAMES)
{
int startScan, minIndex;
string minValue;
for(startScan = 0; startScan < (NUM_NAMES -1); startScan++)
{
minIndex = startScan;
minValue = array[startScan];
for(int index = startScan +1; index < NUM_NAMES; index++)
{
if (array[index] < minValue)
{
minValue = array[index];
minIndex = index;
}
}
array[minIndex] = array[startScan];
array[startScan] = minValue;
}
}
如果有人可以帮助我,我将不胜感激。
答案 0 :(得分:1)
minValue = array[startScan];
您正在为int分配字符串。将minValue
的类型设为string
。然后它应该工作。
答案 1 :(得分:0)
c ++和stl使选择排序更加简单和优雅(字符串或整数)
vector<string> v={"chandler","joey","phoebe","ross","rachel","monica"};
for(auto i=v.begin();i!=v.end();i++)
iter_swap(i, min_element(i,v.end()));
for(auto&x : v) cout<<x<<" ";//printing the sorted vector
如果您没有使用c ++ 14,只需将auto更改为矢量迭代器。
答案 2 :(得分:0)
这可能会有所帮助:
import java.util.Arrays;
public class StringSort {
public static void main(String[] args){
final int nu_names = 20;
String names[ ] = new String[nu_names];
names = new String[]{"Collins, Bill", "Smith, Bert", "Allen, Jim",
"Griffin, Jim", "Stamey, Marty", "Rose, Geri",
"Taylor, Terri", "Johnson, Jim",
"Allison, Jeff", "Looney, joe", "Wolfe, Bill",
"James, Jean", "Weaver, Jim", "Pore, Bob",
"Rutherford, Greg", " Javens, Renee",
"Herrison, Rose", "Setzer, Cathy",
"Pike, Gordon", "Holland, Beth"};
sort(names);
System.out.print(Arrays.toString(names));// print names
}
//sort method
public static void sort(String[] names){
String currentName = "";
int currenIndex = 0;
for(int i = 0; i < names.length - 1; i++){
currentName = names[i];
currenIndex = i;
for(int j = i + 1; j < names.length; j++){
if(currentName.compareTo(names[j]) > 0) {
currentName = names[j];
currenIndex = j;
}
}
swap(names, i,currenIndex );
}
}
//Swap when necessary
public static void swap(String[] names, int a, int b){
String temp = names[a];
names[a] = names[b];
names[b] = temp;
}
}