<span style="font-size:18px;">一下为简单实现:</span>
#define SIZE 3;
typedef int DataType;
typedef struct SeqList
{
DataType *array;
size_t size; //数据实际长度
size_t capicity;//扩展后大小
}SeqList;
//初始化顺序表
void InitSeqList(SeqList *pSeq)
{
pSeq->capicity = SIZE;
pSeq->array = (DataType*)malloc(sizeof(DataType)*pSeq->capicity);
if(NULL == pSeq->array)
{
printf("分配内存shi:\n");
return;
}
pSeq->size = 0;
}
//尾插数据
void PushBack(SeqList *pSeq,DataType x)
{
assert(pSeq);
if(pSeq->size >= pSeq->capicity)//每次插入一个数据,
//size就加一 直到size大于初始容量 就扩容
{
DataType *newpSeq;
pSeq->capicity = (pSeq->capicity)*SIZE;
newpSeq = (DataType*)malloc(sizeof(DataType)*pSeq->capicity);
if(NULL == newpSeq)
{
printf("内存分配失败:\n");
return;
}
memcpy(newpSeq,pSeq->array,sizeof(DataType)*pSeq->size);
free(pSeq->array);
pSeq->array = newpSeq;
pSeq->array[pSeq->size] = x;
pSeq->size++;
}
else
{
pSeq->array[pSeq->size] = x;
pSeq->size++;
}
}
//遍历顺序表
void TraverseList(SeqList *pSeq)
{
int i;
for(i = 0; i < pSeq->size; i++)
{
printf("%d\t",pSeq->array[i]);
}
printf("\n");
}
//冒泡排序
void BubbleSort(SeqList *s)
{
int i, j, temp;
for(i = 0; i < s->size-1; i++)
{
for(j = 0;j < s->size-i-1; j++)
{
if(s->array[j]>s->array[j+1])
{
temp = s->array[j];
s->array[j] = s->array[j+1];
s->array[j+1] = temp;
}
}
}
}
//选择排序
void SeclectSort(SeqList *pSeq)
{
int i, j, k; //设K为最小数的下标
for(i = 0; i < pSeq->size; i++)
{
DataType temp;
k = i;
for(j = i+1; j < pSeq->size; j++)
{
if(pSeq->array[j] < pSeq->array[k])
{
k = j;
}
}
temp = pSeq->array[i];
pSeq->array[i] = pSeq->array[k];
pSeq->array[k] = temp;
}
}
//二分查找
int BinarySearch(SeqList *pSeq,DataType x)
{
int left = 0;
int right = pSeq->size;
while(left < right)
{
int mid = left + (right - left)/2;
if(pSeq->array[mid] < x)
{
left = mid+1;
}
else if(pSeq->array[mid] > x)
{
right = mid;
}
else
{
return mid;
}
}
return -1;
}
//递归 二分查找
int BinarySearch_r(SeqList *pSeq,int left,int right,DataType x)
{
SeqList List;
assert(pSeq);
while(left < right)
{
int mid = left + (right - left)/2;
if(pSeq->array[mid] < x)
{
return BinarySearch_r(&List,mid+1,right,x);
}
else if(pSeq->array[mid] > x)
{
return BinarySearch_r(&List,left,mid,x);
}
else
{
return mid;
}
}
return -1;
}