用c++写一个程序包括构造顺序表,打印顺序表,按位删除,按值查找,选择排序
时间: 2024-03-09 11:44:48 浏览: 19
好的,下面是示例代码:
```c++
#include <iostream>
using namespace std;
const int MAX_SIZE = 100;
class SeqList {
private:
int data[MAX_SIZE];
int length;
public:
SeqList() {
length = 0;
}
~SeqList() {}
void printList() {
for (int i = 0; i < length; i++) {
cout << data[i] << " ";
}
cout << endl;
}
bool insert(int pos, int value) {
if (pos < 0 || pos > length || length >= MAX_SIZE) {
return false;
}
for (int i = length; i > pos; i--) {
data[i] = data[i - 1];
}
data[pos] = value;
length++;
return true;
}
bool remove(int pos) {
if (pos < 0 || pos >= length) {
return false;
}
for (int i = pos; i < length - 1; i++) {
data[i] = data[i + 1];
}
length--;
return true;
}
int search(int value) {
for (int i = 0; i < length; i++) {
if (data[i] == value) {
return i;
}
}
return -1;
}
void selectionSort() {
for (int i = 0; i < length - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < length; j++) {
if (data[j] < data[minIndex]) {
minIndex = j;
}
}
if (minIndex != i) {
int temp = data[i];
data[i] = data[minIndex];
data[minIndex] = temp;
}
}
}
};
int main() {
SeqList list;
list.insert(0, 5);
list.insert(1, 3);
list.insert(2, 8);
list.insert(3, 1);
cout << "Original list: ";
list.printList();
list.remove(2);
cout << "After removing the second element: ";
list.printList();
int pos = list.search(3);
if (pos != -1) {
cout << "3 is found at position " << pos << endl;
} else {
cout << "3 is not found" << endl;
}
list.selectionSort();
cout << "After selection sort: ";
list.printList();
return 0;
}
```
解释:
- `SeqList` 类表示顺序表,包含 `data` 数组和 `length` 成员变量。构造函数初始化 `length` 为 0。
- `printList` 方法用于打印顺序表中的元素。
- `insert` 方法用于在指定位置插入一个元素。
- `remove` 方法用于删除指定位置的元素。
- `search` 方法用于在顺序表中查找指定的元素值,返回该元素的位置,如果没找到则返回 -1。
- `selectionSort` 方法用于对顺序表进行选择排序。
在 `main` 函数中,我们创建一个 `SeqList` 对象 `list`,插入一些元素,打印原始顺序表,删除第二个元素,查找元素 3 的位置,对顺序表进行选择排序,最后再次打印顺序表。