Hanoi implementation of C language and bubble sort

Source: Internet
Author: User

Hanoi is definitely a classic algorithm topic, although it was also said that the program is not long, but always feel that understanding is not clear, see the program can understand what meaning, after a period of time to forget the process, can not think of the time, how do not understand, although said it seems to be so, it is high do not understand. By the first two days to do eight queen of the East Wind, by the way to the Han Nuo tower. Park plate numbered 1, 2 from top to bottom, N, the pole from left to right a,b,c,a is from,c is to. I still read the previous Java program and then I understand the written C program, almost no difference, of course, when writing also forgot a lot, the first time out of the wrong answer. The procedure is as follows:

#include <stdio.h>
#define INIT_NUM 3
int count;
void hanoi(int n, char from, char to, char middle)
{
if (n > 0)
{
count++;
hanoi(n-1, from, middle, to);
printf("Move No.%-2d from %c to %c\n", n, from, to);
hanoi(n-1, middle, to, from);
}
}
int main(int argc, char *argv[])
{
int init = INIT_NUM;
if (argc==2)
init = atoi(argv[1]);
printf("A 是起始杆,C 是辅助杆,B 是目的杆。\n\n");
hanoi(init, 'A', 'C' , 'B');
printf("\nCount = %d", count);
return 0;
}

By this wind, I'll write the algorithm for sorting, I just remember bubble and quick sort, now write a bubble sort bar:

#include <stdio.h>
void show (int *p)
{
int i=0;
for (i=0 ;i<8 ;i++ )
{
printf("%3d ", p[i]);
}
printf("\n");
}
int main(int argc, char *argv[])
{
int p[] = {8, 9, 4, 5, 1, 7, 6, 0};
int i = 0;
int j = 0;
int tmp = 0;
for (i=0 ;i<8 ;i++ )
{
for (j=0 ;j<7-i ;j++ )
{
if (p[j] > p[j+1])
{
tmp = p[j];
p[j] = p[j+1];
p[j+1] = tmp;
}
}
printf("第%2d轮排序结束:", i+1);
show(p);
}
  return 0;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.