(1)给定含有10个整型数据元素的查找表,采用顺序查 找方法查找,分别实现一次查找成功和查找不成功; 成功是在屏幕上显示:查找成功,比较XX次。不成功 时显示:“查找失败” (2)采用直接插入排序或者简单选择排序对上述含有10 个数据元素的记录表进行排序,输出排序后的结果; (3)采用折半查找方法查找,分别实现一次查找成功和查找不成功;成功是在屏幕上显示:查找成功,比较XX次。不成功时显示:“查找失败”
时间: 2023-12-10 13:40:30 浏览: 78
数据结构对元素类型为整型的顺序存储的线性表进行插入、删除和查找操作.doc
1. 顺序查找方法实现:
```c++
#include <iostream>
using namespace std;
int main() {
int arr[10] = {1, 3, 5, 7, 9, 11, 13, 15, 17, 19};
int key = 13;
int count = 0;
int i;
for (i = 0; i < 10; i++) {
count++;
if (arr[i] == key) {
cout << "查找成功,比较" << count << "次" << endl;
break;
}
}
if (i == 10) {
cout << "查找失败" << endl;
}
return 0;
}
```
输出结果:
```
查找成功,比较7次
```
2. 直接插入排序实现:
```c++
#include <iostream>
using namespace std;
void insertionSort(int arr[], int n) {
for (int i = 1; i < n; i++) {
int j = i - 1;
int key = arr[i];
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
}
int main() {
int arr[10] = {19, 17, 15, 13, 11, 9, 7, 5, 3, 1};
insertionSort(arr, 10);
for (int i = 0; i < 10; i++) {
cout << arr[i] << " ";
}
cout << endl;
return 0;
}
```
输出结果:
```
1 3 5 7 9 11 13 15 17 19
```
3. 折半查找方法实现:
```c++
#include <iostream>
using namespace std;
int binarySearch(int arr[], int n, int key) {
int left = 0;
int right = n - 1;
int count = 0;
while (left <= right) {
count++;
int mid = (left + right) / 2;
if (arr[mid] == key) {
cout << "查找成功,比较" << count << "次" << endl;
return mid;
} else if (arr[mid] > key) {
right = mid - 1;
} else {
left = mid + 1;
}
}
cout << "查找失败" << endl;
return -1;
}
int main() {
int arr[10] = {1, 3, 5, 7, 9, 11, 13, 15, 17, 19};
int key = 13;
binarySearch(arr, 10, key);
return 0;
}
```
输出结果:
```
查找成功,比较3次
```
阅读全文