(原)通过合并排序算法加深对边界值(等号的取舍)的认识

 

   1:  #include <iostream>
   2:  #include <stdlib.h>
   3:  #include <time.h>
   4:  using namespace std;
   5:   
   6:  void Merge(int a[], int left, int mid, int right, int* tempA, int* tempB)
   7:  {
   8:      int lengthA = mid - left + 1, lengthB = right - mid;
   9:      int i,j,k;
  10:      for(i=0; i<lengthA; i++)
  11:           tempA[i] = a[left+i];
  12:         for(j=0; j<lengthB; j++)
  13:             tempB[j] = a[mid+1+j];
  14:      i = j = 0;
  15:      k = left;
  16:      while(i < lengthA && j < lengthB)
  17:      {
  18:          if(tempA[i] <= tempB[j])
  19:              a[k++] = tempA[i++];
  20:          else
  21:              a[k++] = tempB[j++];
  22:      }
  23:      
  24:      if(i < lengthA)
  25:      {
  26:          while(i < lengthA)
  27:              a[k++] = tempA[i++]; 
  28:      }
  29:      
  30:      if(j < lengthB)
  31:      {
  32:          while(j < lengthB)
  33:              a[k++] = tempB[j++];
  34:      }
  35:      cout<<"After Merge: "<<left<<"  "<<mid<<"  "<<right<<endl;
  36:      cout<<"|  ";
  37:      for(int m=left; m<=right; m++)
  38:          cout<<a[m]<<"  ";
  39:      cout<<" |"<<endl;
  40:      cout<<endl;
  41:  }
  42:   
  43:  void _MergeSort(int* a, int lo, int hi, int* tempA, int* tempB)
  44:  {
  45:      cout<<lo<<"  "<<hi<<endl;
  46:      if(lo < hi)
  47:        {
  48:             int middle = (hi + lo)/2;
  49:             _MergeSort(a, lo, middle, tempA, tempB);
  50:           _MergeSort(a, middle+1, hi, tempA, tempB);
  51:           Merge(a, lo, middle, hi, tempA, tempB);
  52:        }
  53:  }
  54:   
  55:  void MergeSort(int* a, int length)
  56:  {
  57:      int* tempA = new int[length];
  58:      int* tempB = new int[length];
  59:      _MergeSort(a, 0, length-1, tempA, tempB);
  60:      delete []tempA;
  61:      delete []tempB;
  62:  }
  63:   
  64:  int main()
  65:  {   
  66:      int i,n;
  67:      cin>>n;
  68:      int* a =new int[n];
  69:      srand(time(NULL));
  70:      for(i=0; i<n; i++)
  71:      {
  72:          a[i] = rand()%100 + 1;    
  73:      }
  74:      
  75:      cout<<"Before MergeSort : "<<endl;
  76:      for(i=0; i<n; i++)
  77:           cout<<a[i]<<" ";
  78:      cout<<endl;
  79:      
  80:      MergeSort(a, n);
  81:      
  82:      cout<<endl
  83:          <<"After MergeSort : "<<endl;
  84:      for(i=0; i<n; i++)
  85:           cout<<a[i]<<" ";
  86:   
  87:      delete []a;
  88:      return 0; 
  89:  }

代码如上,当时由于while和if里面的条件没写好,导致数组越界。我总结了一个小技巧,就是用临界值的左边一个和右边一个值去做测试,例如这句

while(i < lengthA && j < lengthB)

当 i=lengthA-1 的时候可以继续执行吗?当 i=lengthA 的时候又可以继续执行吗?根据不同的情况决定是否应该使用等号。

posted @ 2013-07-05 09:54  Wilson Kwok  阅读(358)  评论(0)    收藏  举报