159人阅读 评论(0)

# 顺序表算法补充

<span style="font-size:18px;">//[]
int BinarySearch(SeqList *pSeq, ElemType x)
{
assert(pSeq);
int left = 0;
int right = pSeq->size - 1;
while(left<=right)
{
int cur = left+(right-left)/2;
if(pSeq->array[cur] == x)
{
return cur;
}
else if(pSeq->array[cur]>x)
{
right = cur - 1;
}
else
left = cur + 1;
}
return -1;
}

//////////////////////////////////递归实现二分查找
int BinarySearch_R(SeqList *pSeq,int left,int right ,ElemType x)
{
if (left<=right)
{
int mid = left+(right-left)/2;
if( x== pSeq->array[mid])
return mid;
else if(x<pSeq->array[mid])
return BinarySearch_R(pSeq,left,mid-1,x);
else if(x>pSeq->array[mid])
return BinarySearch_R(pSeq,mid+1,right,x);
}
else
return -1;
}

//////////冒泡排序优化
void  BubbSort_op(SeqList *s)
{
int exchange = 0;
for(size_t i = 0; i < s->size-1;++i)
{
for(size_t j = 0; j < s->size-1-i; ++j)
{
if(s->array[j] > s->array[j+1])
{
ElemType tmp = s->array[j];
s->array[j] = s->array[j+1];
s->array[j+1] = tmp;
exchange = 1;
}
}
if(exchange == 0)
return;
}
}

/////////////////////选择排序
void  SelectSort(SeqList *s)
{
for(size_t i = 0; i < s->size-1;++i)
{
int maxind = i;
for(size_t j = i+1; j < s->size; ++j)
{
if(s->array[j] > s->array[maxind])
maxind = j;
}
//change maxind  and  i;
ElemType tmp = s->array[i];
s->array[i] = s->array[maxind];
s->array[maxind] = tmp;
}
}

/////////////////////选择排序优化
void  SelectSort_op(SeqList *s)
{
int max = s->size-1;
int min = 0;
//从两端往中间走，比较，循环次数缩小一半
while(max >= min)
{
int maxind = max;
int minind = min;
//当遇到刚好[6,5]时，尴尬了。兑换
if(s->array[min]>s->array[max])
{
ElemType tmp1 = s->array[max];
s->array[max] = s->array[min];
s->array[min] = tmp1;
}
///找到最大最小值
for(int i = min;i<=max;++i)
{
if(s->array[i]>s->array[maxind])
{
maxind = i;
}
if(s->array[i]<s->array[minind])
{
minind = i;
}
}
///兑换并缩小范围
ElemType tmp = s->array[minind];
s->array[minind] = s->array[min];
s->array[min] = tmp;
ElemType tmp1 = s->array[maxind];
s->array[maxind] = s->array[max];
s->array[max] = tmp1;
max--;
min++;
}
}</span>


0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：4504次
• 积分：131
• 等级：
• 排名：千里之外
• 原创：8篇
• 转载：0篇
• 译文：0篇
• 评论：5条
文章分类
文章存档
评论排行
最新评论