用C语言实现分治方法数组的排序,C语言实现分治法实例
本文為大家分享了C語(yǔ)言實(shí)現(xiàn)分治法實(shí)例代碼,供大家參考,具體內(nèi)容如下
使用分治法求最大值
這個(gè)函數(shù)將數(shù)組a[l]...a[r]分成a[l],...,a[m]和a[m+1],...a[r]兩部分,分別求出每一部分的最大元素(遞歸地),并返回較大的那一個(gè)作為整個(gè)數(shù)組的最大元素.如果數(shù)組大小是偶數(shù),則兩部分大小相等;如果是奇數(shù),第一部分比第二部分的大小大1.
#include
#include
#include
#include
using namespace std;
#define OK 1
#define ERROR -1
#define TRUE 1
#define FALSE 0
typedef int Status;
int Max(int a[], int l, int r)
{
int u, v, m = (l + r) / 2;
//當(dāng)區(qū)間中只有一個(gè)元素,遞歸終止,并將該元素返回
if(l == r)
return a[l];
//遞歸原區(qū)域的左邊
u = Max(a, l, m);
//遞歸原區(qū)域的右邊
v = Max(a, m+1, r);
//返回最大值
return (u>v)?u:v;
}
int main()
{
//舉例驗(yàn)證
int a[7] = {6, 5, 3, 4, 7, 2, 1};
int maxx = Max(a, 0, 6);
printf("%d\n", maxx);
return 0;
}
漢諾塔的解
我們把盤(pán)子(遞歸地)移動(dòng)到c上的方案是,將除了最下面的盤(pán)子之外的所有盤(pán)子移到b上,然后將做下面的盤(pán)子移到c上,然后(遞歸地)再將其他盤(pán)子移回到最下面的盤(pán)子上面.
#include
#include
#include
#include
using namespace std;
#define OK 1
#define ERROR -1
#define TRUE 1
#define FALSE 0
typedef int Status;
//輸出盤(pán)子的移動(dòng)
void shift(int n, char x, char y)
{
printf("Move %d disk: %c ---------> %c\n", n, x, y);
}
void hanoi(int n, char a, char b, char c)
{
//遞歸終止的條件
if(n == 1)
{
//將a上最下面的盤(pán)子移到c上
shift(n, a, c);
return;
}
//以c為中間軸,將a上的盤(pán)子移動(dòng)到b上
hanoi(n-1, a, c, b);
shift(n, a, c);
//以a為中間軸,將b上的盤(pán)子移動(dòng)到c上
hanoi(n-1, b, a, c);
}
int main()
{
//舉例驗(yàn)證
hanoi(4, 'a', 'b', 'c');
return 0;
}
使用分治法在尺子上畫(huà)刻度
要在尺子上畫(huà)刻度線(xiàn),我們首先在左半邊畫(huà)刻度線(xiàn),然后在中間畫(huà)一條最長(zhǎng)的刻度線(xiàn),最后在右半邊畫(huà)刻度線(xiàn).
#include
#include
#include
#include
using namespace std;
#define OK 1
#define ERROR -1
#define TRUE 1
#define FALSE 0
typedef int Status;
//畫(huà)線(xiàn)
void mark(int m, int h)
{
//由于無(wú)法實(shí)際表示刻度線(xiàn)之間的高度差,故用實(shí)際數(shù)字來(lái)體現(xiàn)
printf("%d ", h);
}
//劃分該區(qū)域內(nèi)的刻度
void rule(int l, int r, int h)
{
//找到該區(qū)域的中間
int m = (l + r) / 2;
//當(dāng)高度大于0
if(h)
{
//劃分小區(qū)域
rule(l, m, h-1);
//畫(huà)線(xiàn)
mark(m, h);
//劃分小區(qū)域
rule(m+1, r, h-1);
}
}
int main()
{
//舉例驗(yàn)證
rule(0, 14, 4);
return 0;
}
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持我們。
時(shí)間: 2018-08-13
總結(jié)
以上是生活随笔為你收集整理的用C语言实现分治方法数组的排序,C语言实现分治法实例的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 欧洲等发达国家央行降息,基准利率竟降至负
- 下一篇: 快递运费险怎么理赔