每个人。我已经被分配了一个课堂作业,我正在尝试做,但是我对措辞感到困惑
“修改选择排序算法以通过增加长度来对字符串数组进行排序。”
现在,这本书来自“ Big C ++ Late Objects Enhanced etext第三版,实践练习12.1。
我对“通过增加长度对字符串数组进行排序的部分感到困惑”。我不知道“增加长度”是什么意思。我以为我必须将算法修改为必须在其中创建一个变量并将其运行到程序运行时将其控制台输入(或cin >>)到该变量的位置,但是我感觉不是我应该的去做。
编辑:4/4/2020
好吧,在查看了有关我的问题的一些信息以及下面的注释之后(感谢用户的帮助,我可以将程序修改为:
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <stdio.h>
#include <string>
using namespace std;
/**
Gets the position of the smallest element in an array range.
@param a the array
@param from the beginning of the range
@param to the end of the range
@return the position of the smallest element in
the range a[from]...a[to]
*/
int min_position(const char a[], int from, int to)
{
int min_pos = from;
for (int i = from + 1; i <= to; i++)
{
if (a[i] < a[min_pos]) { min_pos = i; }
}
return min_pos;
}
/**
Swaps two integers.
@param x the first integer to swap
@param y the second integer to swap
*/
void swap(int& x, int& y)
{
int temp = x;
x = y;
y = temp;
}
/**
Sorts a array using the selection sort algorithm
@param a the array to sort
@param size the number of elements in a
*/
void selection_sort(const char a[], int size)
{
int next; // The next position to be set to the minimum
for (next = 0; next < size - 1; next++)
{
// Find the position of the minimum starting at next
int min_pos = min_position(a, next, size - 1);
// Swap the next element and the minimum
swap(a[next], a[min_pos]);
}
}
/**
Prints all elements in an array.
@param a the array to print
@param size the number of elements in a
*/
void print(const char a[], int size)
{
for (int i = 0; i < size; i++)
{
cout << a[i] << " ";
}
cout << endl;
}
int main()
{
srand(time(0));
const int SIZE = 6;
// changed value to Words
const char * Words[SIZE]={"School" , "To", "Sky" ,"Grade" , "A","Amazing"};
for(unsigned i = 0; i < SIZE; i++)
{
cout<<Words[rand()%SIZE]<<endl;
}
print(Words, SIZE);
selection_sort(Words, SIZE);
print(Words, SIZE);
return 0;
}
我这样做是为了随机选择“单词”字符类型中的单词并将继续这样做,将最短的单词分类为最长的单词并将其打印出来。请注意,该工作目前正在进行中。
现在对我来说,问题是我似乎无法调用“ print”和“ selection_sort”的函数,而且我知道,冰山一角只是需要做的事情。我知道我可以使用str.length来对单词进行排序,但是现在我想专注于调用该函数,所以任何建议
它们可能表示字符串中字符的长度。如果您使用字符串size()或length()方法,它将返回字符串中的字符数。
如果在每个字符串上使用此函数,将有一个可以按升序排序的整数数组。
它们可能表示字符串中字符的长度。如果您使用字符串size()或length()方法,它将返回字符串中的字符数。
如果在每个字符串上使用此函数,将有一个可以按升序排序的整数数组。