目录
汉诺塔问题
#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
7
输出
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;
}
本文介绍了如何使用递归解决汉诺塔问题,并提供了C语言的代码实现。同时,文章讲解了寻找数组中第K大数的算法,通过快速选择的方法有效地找到目标值,同样给出了相应的C语言实现。这两个经典算法在计算机科学中有着广泛的应用。
1016

被折叠的 条评论
为什么被折叠?



