顺序表的插入,删除和排序(排序需要有两种,直接排序和冒泡排序)生成完整代码
时间: 2024-02-19 15:04:08 浏览: 18
好的,下面是使用C++实现顺序表的插入、删除和排序操作的完整代码:
```cpp
#include <iostream>
#include <algorithm>
using namespace std;
const int MAXSIZE = 100; // 顺序表最大长度
// 顺序表结构体
struct List {
int data[MAXSIZE]; // 存储数据元素的数组
int length; // 顺序表长度
};
// 初始化顺序表
void initList(List &L) {
L.length = 0;
}
// 插入操作
bool insertList(List &L, int pos, int val) {
if (pos < 1 || pos > L.length + 1 || L.length == MAXSIZE) {
return false;
}
for (int i = L.length; i >= pos; i--) {
L.data[i] = L.data[i - 1];
}
L.data[pos - 1] = val;
L.length++;
return true;
}
// 删除操作
bool deleteList(List &L, int pos) {
if (pos < 1 || pos > L.length) {
return false;
}
for (int i = pos - 1; i < L.length - 1; i++) {
L.data[i] = L.data[i + 1];
}
L.length--;
return true;
}
// 直接排序
void directSort(List &L) {
for (int i = 0; i < L.length - 1; i++) {
for (int j = i + 1; j < L.length; j++) {
if (L.data[i] > L.data[j]) {
swap(L.data[i], L.data[j]);
}
}
}
}
// 冒泡排序
void bubbleSort(List &L) {
for (int i = 0; i < L.length - 1; i++) {
for (int j = 0; j < L.length - i - 1; j++) {
if (L.data[j] > L.data[j + 1]) {
swap(L.data[j], L.data[j + 1]);
}
}
}
}
// 打印顺序表
void printList(List &L) {
for (int i = 0; i < L.length; i++) {
cout << L.data[i] << " ";
}
cout << endl;
}
int main() {
List L;
initList(L);
// 插入操作
insertList(L, 1, 5);
insertList(L, 2, 3);
insertList(L, 3, 7);
insertList(L, 4, 2);
insertList(L, 5, 9);
cout << "插入操作后的顺序表: ";
printList(L);
// 删除操作
deleteList(L, 3);
cout << "删除操作后的顺序表: ";
printList(L);
// 直接排序
directSort(L);
cout << "直接排序后的顺序表: ";
printList(L);
// 冒泡排序
bubbleSort(L);
cout << "冒泡排序后的顺序表: ";
printList(L);
return 0;
}
```
注意,在实现插入和删除操作时,我们需要判断插入或删除的位置是否合法,以及顺序表是否已满或为空。同时,插入操作需要将插入位置后面的元素依次后移一位,删除操作需要将删除位置后面的元素依次前移一位。在实现排序操作时,我们可以使用STL库中的`swap`函数交换两个元素的值。