美文网首页
循环语句的小建议

循环语句的小建议

作者: wild_horse | 来源:发表于2017-03-12 18:18 被阅读0次

int partition(int num[],int lo,int hi)
{
    swap(num[lo],num[rand()%(hi-lo+1)+lo]);
    int pivot=num[lo];
    while(lo<hi)
    {
        while(lo<hi && pivot<=num[hi]) hi--;
        num[lo]=num[hi];
        while(lo<hi && pivot>=num[lo]) lo++;
        num[hi]=num[lo];
    }
    num[lo]=pivot;
    return lo;
}

如果在while循环中对索引进行操作,必须添加索引不越界的条件

void Merge(int num[],int lo,int mid,int hi)
{
    int A[]=num+lo;
    int la=hi-lo;
    int lb=mid-lo;
    int B[]=new int[lb];  //----------------------
    for(int i=0;i<lb;i++)
        B[i]=A[i];
    int C[]=num+mid;
    int lc=hi-mid;
    
    for(int i=0,j=0,k=0;j<lb;)
    {       
        if(k<lc && B[j]>=C[k])  //防止越界访问
            A[i++]=C[k++];
        if(k>=lc || B[j]<C[k])  //使用 if 不使用 while 
                                //每一次 for 循环,j 最多增加 1,条件判断,防止越界
                                //若是加入 while 循环,要在 for 内部对 j 进行判断,防止 j
                                // 增加多位,发生越界访问
            A[i++]=B[j++];      //而且 先判断 C 段,再判断 B段,减少一个条件 j<jb
        
    }
    
    delete [] B;
}

在Merge函数中,for中嵌套if语句,要保证每次索引j操作的增量都不大于一,可以不在 if中判断越界。

相关文章

网友评论

      本文标题:循环语句的小建议

      本文链接:https://www.haomeiwen.com/subject/xhcxnttx.html