C語言實現快速排序法(分治法)



title: 快速排序法(quick sort)
tags: 分治法(divide and conquer method)
grammar_cjkRuby: true

算法原理

分治法的基本思想:將原問題分解為若干個更小的與原問題相似的問題,然后遞歸解決各個子問題,最后再將各個子問題的解組合成原問題的解。
利用分治法可以將解決辦法分為 “三步走” 戰略:
(1) 在數據集中選定一個元素作為“基准”(pivot)
(2) 將所有數據集小於基准的元素放在基准左邊,大於基准的元素放在基准右邊,把原數據集分為兩個數據集的操作叫做“分區”,分區結束后基准所在的位置也就是基准最后的位置
(3) 分別對基准左右兩邊的數據集進行前兩個步驟,直至數據集只剩下一個數據為止
enter description here

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;
}

實例分析

enter description here

(1)取5作為pivot,然后將其移動到最后一個位置
(2)從第一個數3到倒數第二個數5分別和pivot比較,如果小於等於pivot的數依次從前向后排
(4)將pivot 5移回兩個分區中間


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM