用c++完成,不用sort函数请用户输入10首歌名,歌名存入一字符指针数组,然后分别按原序、字母序和字母逆序(从Z到A)显示这些歌名。
时间: 2024-10-20 07:08:07 浏览: 33
STL.zip_C++STL
在C++中,你可以通过自定义排序算法来实现这个需求。首先,你需要创建一个动态内存分配的字符数组存储歌名,并让用户输入数据。接下来,我们编写三个函数分别按照原顺序、字母顺序和逆字母顺序对歌名进行排序:
```cpp
#include <iostream>
#include <string>
// 原始顺序(无排序)
void displayOriginalOrder(char* songs[], int size) {
for (int i = 0; i < size; ++i) {
std::cout << songs[i] << " ";
}
std::cout << std::endl;
}
// 字母顺序(升序)
void displayAlphabeticalOrder(char* songs[], int size) {
// 自己实现冒泡排序或者快速排序等,这里简化为直接遍历
bool swapped;
for (int i = 0; i < size - 1; ++i) {
swapped = false;
for (int j = 0; j < size - i - 1; ++j) {
if (*songs[j] > *songs[j + 1]) {
char temp = *songs[j];
*songs[j] = *songs[j + 1];
*songs[j + 1] = temp;
swapped = true;
}
}
if (!swapped)
break; // 如果已经有序则提前结束
}
for (int i = 0; i < size; ++i) {
std::cout << songs[i] << " ";
}
std::cout << std::endl;
}
// 字母逆序(降序)
void displayReverseAlphabeticalOrder(char* songs[], int size) {
// 类似字母顺序,但判断条件相反
for (int i = 0; i < size - 1; ++i) {
bool swapped;
for (int j = 0; j < size - i - 1; ++j) {
if (*songs[j] < *songs[j + 1]) { // 交换条件反转
char temp = *songs[j];
*songs[j] = *songs[j + 1];
*songs[j + 1] = temp;
swapped = true;
}
}
if (!swapped)
break; // 提前结束
}
for (int i = 0; i < size; ++i) {
std::cout << songs[i] << " ";
}
std::cout << std::endl;
}
int main() {
const int MAX_SONGS = 10;
char* songNames[MAX_SONGS];
for (int i = 0; i < MAX_SONGS; ++i) {
std::cout << "请输入第" << (i + 1) << "首歌名: ";
std::cin.getline(songNames[i], sizeof(songNames[i])); // 用户输入
}
std::cout << "原始顺序: ";
displayOriginalOrder(songNames, MAX_SONGS);
std::cout << "字母顺序: ";
displayAlphabeticalOrder(songNames, MAX_SONGS);
std::cout << "字母逆序: ";
displayReverseAlphabeticalOrder(songNames, MAX_SONGS);
return 0;
}
```
阅读全文