递归问题复习

本文介绍了如何使用递归解决汉诺塔问题,并提供了C语言的代码实现。同时,文章讲解了寻找数组中第K大数的算法,通过快速选择的方法有效地找到目标值,同样给出了相应的C语言实现。这两个经典算法在计算机科学中有着广泛的应用。
摘要由CSDN通过智能技术生成

目录

汉诺塔问题

求一组数中的第K大数


汉诺塔问题

#include <stdio.h>
void Move(int n, char start, char goal,char temp) 
{
	if(n >= 1)
	{
		Move(n-1, start, temp, goal);
		printf("%c -> %c\n", start, goal);
		Move(n-1, temp, goal, start);
	}
}
int main()
{
	int n;
	scanf("%d", &n);
	char a = 'a' , b = 'b', c = 'c';
	Move(n, a, c, b);
	return 0;
}

求一组数中的第K大数

输入

9

6 5 9 8 2 1 7 3 4

5

 输出

5

输入

9

6 5 9 8 2 1 7 3 4

输出

 3

#include <stdio.h>
#include <stdlib.h>
void swap(int *x, int *y);
int FindKthLargest(int s[], int K, int Left, int Right);
int main()
{
	int N;
	scanf("%d", &N);
	int *s;
	s = (int *)malloc(sizeof(int) * N);
	int i;
	for(i = 0; i < N; i++)
	{
		scanf("%d", &s[i]);
	}
	int K;
	scanf("%d", &K);
	printf("%d",FindKthLargest(s, K, 0, N-1));
	return 0;
 } 
void swap(int *x, int *y)
{
	int t;
	t = *x; *x = *y; *y = t;
}
int FindKthLargest(int s[], int K, int Left, int Right)
{
	int e = s[Left];
	int L = Left, R = Right;
    while(1)
	{
		while(s[Left] >= e) Left++;
		while(s[Right] < e) Right--;
		if(Left < Right) swap(&s[Left], &s[Right]);
		else break;
	}
	swap(&s[L], &s[Left-1]);
	if((Left-L) > K) 
	   return FindKthLargest(s, K, L, Left-2);
	else if((Left-L) < K)
	   return FindKthLargest(s, K-(Left-L), Left, R);
	else return e;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值