已知一个顺序表 L,其中的元素递增有序排列,设计一个算法,插入一个元素 x(x 为 int 型)后保持该顺序表仍然递增有序排列(假设插入操作总能成功)。

/*
 * ==============================================================
 * File name:        insert_sorted.c
 * Author:           3360652783@qq.com
 * Date created:     2026-07-22
 * Description:      Insert an element into an increasing sequential list while maintaining order.
 * Copyright notice: All right Reserved
 * ==============================================================
 */

//构建一个向顺序表中插入元素的函数
void SeqList_Insert(*L,int x){        //L是指向顺序表首地址的指针
    int temp = -1;
    for(int i=0;i<Length;i++){       //与顺序表中的每个元素进行比较,Length为元素总个数
        if(x<L[i]){
            temp = i;
            break;
        }
    }
    if(temp==-1){                    //x是最大的数,直接插在顺序表最后面
        L[Length] = x;
        Length++;
    }
    else{
        for(int i=Length;i>temp;i--){       //x排在中间,插入中间
            L[i] = L[i-1];
            L[temp] = x;
            Length++;
        }
    }
}
posted @ 2026-07-22 20:45    阅读(2)  评论(0)    收藏  举报