快速排序——C語言實現

void exchange(int* x, int* y)
{
  int temp = *x;
  *x = *y;
  *y = temp;
}
// 快速排序是一種原址排序,不須要分配新的數組空間
// start和end爲子數組的起始位置與終止位置
int partition(int *arr, int start, int end)
{
  int temp;
  // 獲取主元
  int key = arr[end];
  // left不存在,故將i去值爲start-1
  int i = start - 1;
  for (int j = start; j < end; j++)
  {
    if (arr[j] <= key)
    {
      i = i + 1;
      exchange(arr + i, arr + j);
    }
  }
  exchange(arr + i + 1, arr + end);
  return i + 1;
}
void quickSort(int *arr, int start, int end)
{
  if (start < end)
  {
    int mid = partition(arr, start, end);
    quickSort(arr, start, mid - 1);
    quickSort(arr, mid + 1, end);
  }
}

快速排序分割數組的過程
快排子數組維護了四個不一樣區間

圖片是從算法導論截取的。我的以爲看懂上面這兩幅圖,就理解了快排的思路。
上面這兩張圖是數組分割的過程,整個快速排序就是數組分割,而後在子數組上繼續遞歸調用快排。
下面是分割以及快排的僞代碼,for循環中的to表示小於等於
partition(A, start, end)
    key = A[end]
    i = start - 1
    for j = start to end - 1
        if A[j] <= key
            i = i + 1
            exchange A[i] with A[j]
    exchange A[i+1] with A[j]
    
quickSort(A, start, end)
    if start < end
        mid = partition(A, start, end)
        quickSort(A, start, mid - 1)
        quickSort(A, mid + 1, end)
相關文章
相關標籤/搜索