分治——快速排序

int split(int low, int high, vector&A)
{
   int i = low, x = A[low];      //i总是指向小于A[low]的数的最后一个数
   int tmp = 0;
   for (int j = low + 1; j <= high; ++j)
   {
       if (A[j] <= x)
       {
           i++;
           if (i != j)    //如果i==j,说明不需要交换,该位置正好可以作为小于A[low]的最后一个位置
           {
               tmp = A[j];
               A[j] = A[i];
               A[i] = tmp;
           }
       }
   }
   tmp = A[i];
   A[i] = A[low];
   A[low] = tmp;
   return i;
}
void quick_sort(vector&A, int low, int high)
{
   if (low < high)
   {
       int w = split(low, high, A);
       quick_sort(A, low, w - 1);
       quick_sort(A, w + 1, high);
   }
}

你可能感兴趣的:(分治——快速排序)