1.有我们101个学生的成绩,编程实现:“查找成绩等于某一个特定的成绩,若查找成功则指明位序,若失败则提示成绩不存在”
(1)用数组存放这组成绩,实现顺序查找算法;
(2)用链表存放这组成绩,实现顺序查找算法;
要求:1.编写C语言或C++源代码,调试成功,运行结果截图;2.形成实验报告(电子版),包括:(1)题目要求及分析;(2)设计:逻辑结构,存储结构,算法描述(如流程图);(3)运行过程,结果分析,效率分析;(4)结论
【以下回答由 GPT 生成】
题目要求实现一个查找特定成绩的功能,并指明该成绩在数组或链表中的位置。如果查找成功,则返回该成绩在数组或链表中的位置;如果查找失败,则提示该成绩不存在。
逻辑结构包括将学生的成绩存储在数组或链表中。
存储结构可以选择使用数组或链表来实现。
顺序查找算法 1. 初始化查找位置为-1。 2. 遍历数组或链表,逐个比较成绩与目标成绩。 - 如果找到目标成绩,将查找位置设为当前位置。 3. 如果查找位置不为-1,则输出查找位置和对应的成绩; 否则,输出提示信息成绩不存在。
#include <iostream>
#include <vector>
using namespace std;
// 基于数组的顺序查找实现
int sequentialSearchArray(vector<int>& scores, int target) {
int position = -1;
for (int i = 0; i < scores.size(); i++) {
if (scores[i] == target) {
position = i;
break;
}
}
return position;
}
// 基于链表的顺序查找实现
struct Node {
int score;
Node* next;
};
int sequentialSearchLinkedList(Node* head, int target) {
Node* current = head;
int position = -1;
int index = 0;
while (current != nullptr) {
if (current->score == target) {
position = index;
break;
}
current = current->next;
index++;
}
return position;
}
int main() {
// 数组实现
vector<int> scores = {80, 95, 90, 85, 88, 92, 89, 97, 93, 87};
int targetScoreArray = 88;
int positionArray = sequentialSearchArray(scores, targetScoreArray);
if (positionArray != -1) {
cout << "The target score " << targetScoreArray << " is at position " << positionArray << " in the array." << endl;
} else {
cout << "The target score " << targetScoreArray << " does not exist in the array." << endl;
}
// 链表实现
Node* head = nullptr;
Node* tail = nullptr;
int targetScoreLinkedList = 93;
int positionLinkedList = -1;
vector<int> scoreList = {80, 95, 90, 85, 88, 92, 89, 97, 93, 87};
for (int score : scoreList) {
Node* newNode = new Node();
newNode->score = score;
newNode->next = nullptr;
if (head == nullptr) {
head = newNode;
tail = newNode;
} else {
tail->next = newNode;
tail = newNode;
}
}
positionLinkedList = sequentialSearchLinkedList(head, targetScoreLinkedList);
if (positionLinkedList != -1) {
cout << "The target score " << targetScoreLinkedList << " is at position " << positionLinkedList << " in the linked list." << endl;
} else {
cout << "The target score " << targetScoreLinkedList << " does not exist in the linked list." << endl;
}
return 0;
}
The target score 88 is at position 4 in the array.
The target score 93 is at position 8 in the linked list.
通过使用数组或链表的顺序查找算法,可以实现对特定成绩的查找,并返回在数组或链表中的位置。如果查找成功,则输出位置信息;如果查找失败,则输出提示信息。顺序查找算法的时间复杂度为O(n),空间复杂度为O(n)。
【相关推荐】