顺序表的插入操作:线性表非递减排序,插入一个元素后,使排序仍按照非递减
基本思路:检验插入元素与线性表元素的大小,寻找到合适的位置即插入,注意当插入元素大于最后一个元素和小于第一个元素时,需要单独讨论
void InsertOperate(int *sequence, int &len, int x)
{
if (x > sequence[len-1]) //插入值比最后一个大
{
sequence[len] = x;
len = len +1;
}
if(x < sequence[0])//插入值比第一个小
{
for( int j = len-1; j >= 0; j--)
{
sequence[j+1] = sequence[j];
}
sequence[0] = x;
len = len +1;
}
for(int i = 1; i < len; i++)
{
if(sequence[i-1] < x && sequence[i] > x)
{
for( int j = len-1; j >= i; j--)
{
sequence[j+1] = sequence[j];
}
sequence[i] = x;
len = len +1;
}
}
}
附上整体程序:
//顺序表的删除操作(删除值为x的元素,假设线性表中有若干个x元素)
#include <iostream>
#include <vector>
using namespace std;
//插入元素:线性表非递减排序,插入一个元素后,使排序仍按照非递减
void InsertOperate(int *sequence, int &len, int x)
{
if (x > sequence[len-1]) //插入值比最后一个大
{
sequence[len] = x;
len = len +1;
}
if(x < sequence[0])//插入值比第一个小
{
for( int j = len-1; j >= 0; j--)
{
sequence[j+1] = sequence[j];
}
sequence[0] = x;
len = len +1;
}
for(int i = 1; i < len; i++)
{
if(sequence[i-1] < x && sequence[i] > x)
{
for( int j = len-1; j >= i; j--)
{
sequence[j+1] = sequence[j];
}
sequence[i] = x;
len = len +1;
}
}
}
void PrintElement(int *sequence, int len)
{
for(int count = 0; count < len; count++)
cout << sequence[count] << " " ;
}
int main ()
{
int len = 6;
int sequence[6] = {1,2,2,4,5,6};
int *seq = &sequence[0];
PrintElement(seq, len);
//DeleteOperate(seq,len, 2);
InsertOperate(seq, len, 3);
cout << endl;
PrintElement(seq, len);
system("pause");
return 0;
}