已知线性表L递增有序。试写一算法,将X插入到L的适当位置上,以保持线性表L的有序性

已知线性表L递增有序。试写一算法,将X插入到L的适当位置上,以保持线性表L的有序性。

//
// Created by wp on 2020/3/5.
//已知线性表L递增有序。试写一算法,将X插入到L的适当位置上,以保持线性表L的有序性。
//

#include <iostream>
#include <string>

using namespace std;
#define MAX 1000

class List_wp {
public:
    List_wp() {//初始化列表
        index = 0;
        list_array[index] = 0;
    }

    void append(const int &a) {//向列表添加数字
        list_array[index] = a;
        index++;
    }

    void Appropriate_insertion(const int &x) {//将X插入到L的适当位置上
        for (int i = 0; i < index; i++) {
            if (x <= list_array[i]) {
                yidong(i, x);
                return;
            }
        }
    }

    void list_sort() {//对列表进行排序
        for (int i = 0; i < index - 2; i++) {
            for (int j = 0; j < index - 1 - i; j++) {
                if (list_array[j] > list_array[j + 1]) {
                    int temp = list_array[j];
                    list_array[j] = list_array[j + 1];
                    list_array[j + 1] = temp;
                }
            }
        }
    };

    int len() {//返回列表的长度
        return index;
    }

    void print_list() {//打印列表的数据
        if (index == -1) {
            cout << "list is empty" << endl;
            return;
        }
        for (int i = 0; i < index; i++) {
            if (index != 0) {
                cout << list_array[i];
            }
            if (i == index - 1) {
                cout << endl;
            } else {
                cout << " , ";
            }
        }
    }

private:
    int index;//index
    int list_array[MAX];//保存的数字序列

    void yidong(int m_index, int m_num) {
        index++;
        for (int i = index; i > m_index; i--) {
            list_array[i] = list_array[i - 1];
        }
        list_array[m_index] = m_num;
    }
};


int main() {
    List_wp L;
    L.append(1);//用append向列表中添加元素
    L.append(6);
    L.append(4);
    L.append(2);
    L.append(1);

    L.list_sort();//让线性表L递增有序
    L.print_list();//打印列表的数据
    cout << L.len() << endl;//打印列表的长度

    cout << "---------" << endl;

    L.Appropriate_insertion(3);//将X插入到L的适当位置上
    L.print_list();//打印列表的数据
    cout << L.len() << endl;//打印列表的长度

    return 0;
}
  • 8
    点赞
  • 38
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值