C語言實現快速排序法(分治法)
阿新 • • 發佈:2017-11-15
下一個 enter hang partition 等於 就是 tor log markdown
title: 快速排序法(quick sort)
tags: 分治法(divide and conquer method)
grammar_cjkRuby: true
---
算法原理
分治法的基本思想:將原問題分解為若幹個更小的與原問題相似的問題,然後遞歸解決各個子問題,最後再將各個子問題的解組合成原問題的解。
利用分治法可以將解決辦法分為 “三步走” 戰略:
(1) 在數據集中選定一個元素作為“基準”(pivot)
(2) 將所有數據集小於基準的元素放在基準左邊,大於基準的元素放在基準右邊,把原數據集分為兩個數據集的操作叫做“分區”,分區結束後基準所在的位置也就是基準最後的位置
(3) 分別對基準左右兩邊的數據集進行前兩個步驟,直至數據集只剩下一個數據為止
C語言實現
/***********************/ //章節:第四章 //內容:快速排序 /***********************/ #include<stdio.h> #include<string.h> #include<stdlib.h> #include<sys/stat.h> void fastsort(int v[], int first, int last); int main() { int i, v[10] = {1,243,43,5,6,634,434,23,12,7}; fastsort( v, 0, 9); for(i = 0; i < 10; i++) printf("%d ",v[i]); return 0; } void fastsort(int v[], int first, int last){ int i, storeindex; void swap(int v[], int i, int j); if(first >= last) return; //fewer than two ele swap(v, last, (first + last)/2); //move partition elem storeindex = first; for(i = first; i <= last-1; i++) if(v[i] <= v[last]) { swap(v, storeindex, i); storeindex += 1; } swap(v, last, storeindex); fastsort(v, first, storeindex - 1); fastsort(v, storeindex + 1, last); } /*swap:interchange v[i] and v[j]*/ void swap(int v[], int i, int j){ int temp; temp = v[j]; v[j] = v[i]; v[i] = temp; }
實例分析
(1)取5
作為pivot,然後將其移動到最後一個位置
(2)從第一個數3
到倒數第二個數5
分別和pivot比較,如果小於等於pivot的數依次從前向後排
(4)將pivot 5
移回兩個分區中間
C語言實現快速排序法(分治法)