题目:
已知顺序表L递增有序,试写一算法,将X插入到线性表的适当位置,以保持线性表的有序性。
思路:
从右往左遍历顺序表,如果i不大于X,则右移一位,直到结束。
代码:
#include#include #define MAXSIZE 101typedef struct { int r[MAXSIZE]; int length;} SqList;int main(int argc, char *argv[]) { SqList list; int i, x = 1;; list.length = 5; for (i = 0; i < list.length; i++) { list.r[i] = i * 3; } printf("初始顺序表:\n"); for (i = 0; i < list.length; i++) { printf("%d\t", list.r[i]); } printf("\n"); if (list.length + 1 > MAXSIZE) { printf("数组溢出!"); return 0; } for (i = list.length; list.r[i] > x && i > -1; i--) { list.r[i + 1] = list.r[i]; } list.r[++i] = x; list.length++; printf("插入X后的顺序表:\n"); for (i = 0; i < list.length; i++) { printf("%d\t", list.r[i]); } return 0;}