程序员常见面试题之快排、归并非递归算法

来源:互联网 发布:vmware mac 使用教程 编辑:程序博客网 时间:2024/05/16 12:11

快排和归并是八大排序算法中常常被用作面试题,而且往往是问非递归的算法,代码实现如下:

//归并排序void Merge(vector<int>&A, int p, int q, int r)  {      vector<int> L(A.begin() + p, A.begin() + q+1);   //A[p......q]      vector<int> R(A.begin() + q+1, A.begin() + r+1); //A[q+1......r]      L.push_back(INT_MAX);      R.push_back(INT_MAX);      for (int i = 0, j = 0, k = p; k <= r; k++)      {          if (L[i] <= R[j]) A[k] = L[i++];          else A[k] = R[j++];      }  }/** merge_sort: 非递归实现 --迭代  * 非递归思想: 将数组中的相邻元素两两配对。用merge函数将他们排序,  * 构成n/2组长度为2的排序好的子数组段,然后再将他们排序成长度为4的子数组段,  * 如此继续下去,直至整个数组排好序。  **/  // merge_sort(): 非递归实现-自底向上  // 将原数组划分为left[min...max] 和 right[min...max]两部分  void merge_sort(vector<int> &list)  {      int length = list.size();      vector<int> temp(length, 0);      int i, left_min, left_max, right_min, right_max, next;      for (i = 1; i < length; i *= 2) // i为步长,1,2,4,8……      {          for (left_min = 0; left_min < length - i; left_min = right_max)          {              right_min = left_max = left_min + i;              right_max = left_max + i;              if (right_max > length)                  right_max = length;              next = 0;              while (left_min < left_max && right_min < right_max)                  temp[next++] = list[left_min] > list[right_min] ? list[right_min++] : list[left_min++];                            while (left_min < left_max)                  list[--right_min] = list[--left_max];                while (next > 0)                  list[--right_min] = temp[--next];          }      }  }//快排非递归实现://数据规模很大时,递归的算法很容易导致栈溢出,改为非递归,模拟栈操作,//最大长度为n,每次压栈时先压长度较大的,此时栈深度为logn。int partition(vector<int>& A, int p, int r) {      int x = A[r];      int i = p;      for (int j = p;j < r;j++) {          if (A[j] <= x) {              swap(A[j], A[i]);              i++;          }      }      swap(A[r], A[i]);      return i;  }/**使用栈的非递归快速排序**/  template<typename Comparable>  void quicksort2(vector<Comparable> &vec,int low,int high){      stack<int> st;      if(low<high){          int mid=partition(vec,low,high);          if(low<mid-1){              st.push(low);              st.push(mid-1);          }          if(mid+1<high){              st.push(mid+1);              st.push(high);          }          //其实就是用栈保存每一个待排序子串的首尾元素下标,下一次while循环时取出这个范围,对这段子序列进行partition操作          while(!st.empty()){              int q=st.top();              st.pop();              int p=st.top();              st.pop();              mid=partition(vec,p,q);              if(p<mid-1){                  st.push(p);                  st.push(mid-1);              }              if(mid+1<q){                  st.push(mid+1);                  st.push(q);              }                 }      }  }