學習演算法(5) 快速排序

2021-08-01 02:57:15 字數 1382 閱讀 9959

快速排序,很經典,無數的地方都提到。

**,雖然看起來不多,但是理解起來,並不是很容易。

我花了很長時間,才弄明白。

下面的**,最關鍵的地方,就是理解 i 和 j 的增長的意義。

關鍵核心理解

j   :   序號小到大,做陣列輪詢。

i   :    始終停留在比pivot大的數字的前乙個座標上。這個座標之前的數字都小於pivot 或者 i=-1 。

/* c implementation quicksort */

#include// a utility function to swap two elements

void swap(int* a, int* b)

/* this function takes last element as pivot, places

the pivot element at its correct position in sorted

array, and places all smaller (smaller than pivot)

to left of pivot and all greater elements to right

of pivot */

int partition (int arr, int low, int high)

}swap(&arr[i + 1], &arr[high]);

return (i + 1);

}/* the main function that implements quicksort

arr --> array to be sorted,

low --> starting index,

high --> ending index */

void quicksort(int arr, int low, int high)

}/* function to print an array */

void printarray(int arr, int size)

// driver program to test above functions

int main()

; int n = sizeof(arr)/sizeof(arr[0]);

quicksort(arr, 0, n-1);

printf("sorted array: \n");

printarray(arr, n);

return 0;

}

----

排序演算法5 快速排序

1.什麼是快速排序 快速排序是由東尼 霍爾所發展的一種排序演算法。在平均狀況下,排序 n 個專案要 nlogn 次比較。在最壞狀況下則需要 n 次比較,但這種狀況並不常見。事實上,快速排序通常明顯比其他 nlogn 演算法更快,因為它的內部迴圈 inner loop 可以在大部分的架構上很有效 率地...

排序演算法5 快速排序

快速排序是對氣泡排序基礎上的優化版本,它打破了氣泡排序只能比對交換相鄰元素的方式,並加入了 分治 思想 1 對一串行,選定最左邊的元素作為基數p 再定義i,使i依次從左到右尋找比基數p大的元素 再定義j,使j依次從右到左尋找比基數p小的元素 當i j每每找到,便交換i j元素,直到i j相遇 2 將...

排序演算法5之快速排序

快速排序可以分解為三步 尋找基準數,比較通常就是選擇待排序的首專案或者中間專案 2.根據與基準數的大小關係,將待排序陣列分成兩個子串行 和。其中 均小於基準數,均大於基準數,這樣基準數的位置就確定了在q處。然後利用遞迴對兩個子串行進行排序。下圖是對步驟2的介紹,只是該圖是將基準元素設定為最後乙個元素...