Data structure & Algorithm
  • Initial page
  • 1212
  • 121231
  • 2.algorithm
    • 2.1.backtracking
      • 2.1.1.連續序列的排列組合(可能會重複)
      • 2.1.3.一串數列中任取n個數字, 總共有幾種組合
      • 2.1.2.一串數列中取n個數字, 共有幾種組合
    • 2.5.Quick sort
    • 2.6.2.6.廣度優先搜尋 (Breadth-first Search)
    • 2.2.Binary Search
    • 2.1.Backtracking
    • 2.4.河內塔 (Tower of Hanoi)
    • 2.7.動態規劃
    • 2.8.深度優先搜尋 (Depth-first Search)
    • 2.7.二分搜尋法
    • 2.3.分治法 (Divide and Conquer)
  • 2.Count and Say
  • 1.Leetcode Algorithm Practice
  • 2-count-and-say
    • c-solution
    • javascript-solution
  • Algorithm
  • 123
Powered by GitBook
On this page

Was this helpful?

  1. 2.algorithm

2.5.Quick sort

Previous2.1.2.一串數列中取n個數字, 共有幾種組合Next2.6.2.6.廣度優先搜尋 (Breadth-first Search)

Last updated 5 years ago

Was this helpful?

  • Introduction

    • 目前被認為效率最高的排序演算法(sorting algorithm)

    • 快速排序法也是利用,不斷地將資料分成兩部分以解決問題

      • 最佳時間複雜度:O(nlog n)

      • 平均時間複雜度:O(nlog n)

      • 最差時間複雜度:O(n2)

      • 空間複雜度:O(n)

    • 實作步驟:

      • 1.選擇序列中的一個數字為pivot(通常為最左邊的數字)

      • 2.將此序列中大於pivot的數字放到pivot右邊, 小於pivot的放到pivot左邊

      • 3.以pivot為中心, 將左半部與右半部各自進行步驟1~2

  • 程式碼

void quicksort(int *data, int left, int right)
{
    if (left >= right){
        //function結束
        return;
    }
    //choose data[left] to be the pivot
    int pivot = data[left];
    int i = left + 1;
    int j = right;
    while (1){
        //找出大於pivort的數值
        while (i <= right){
            if (data[i] > pivot){
                break;
            }
            i = i + 1;
        }
        //找出大於pivort的數值
        while (j > left){
            if (data[j] < pivot){
                break;
            }
            j = j - 1;
        }
        //j會先結束while, 當i > j時跳出迴圈 
        if (i > j){
            break;
        }
        //將左右位置互換
        swap(&data[i], &data[j]);
    }
    //將左右位置互換
    swap(&data[left], &data[j]);
    quicksort(data, left, j - 1);
    quicksort(data, j + 1, right);    
}
void swap(int *a, int *b)
{
    int temp = *b;
    *b = *a;
    *a = temp;
}
divide and conquer
時間複雜度, 空間複雜度