Common Algorithms for C Programming

Publisher:数字奇迹Latest update time:2014-09-01 Source: eefocus Reading articles on mobile phones Scan QR code
Read articles on your mobile phone anytime, anywhere
  Algorithm: The basic idea, method and steps for computer problem solving. Algorithm description: It is a description of the methods and steps taken to solve a problem or complete a task, including what data is needed (what data is input, what result is output), what structure is used, what statements are used and how to arrange these statements. Natural language, structured flow charts, pseudocode, etc. are usually used to describe algorithms.

  1. Simple algorithms such as counting, summing, and factorials .

  Such problems all require loops. Pay attention to determining the initial value, final value or end condition of the loop variable according to the problem, and pay more attention to the initial value of the variable used to represent the count, sum, and factorial.

  Example: Use a random function to generate 100 random integers in the range of [0, 99], count the number of numbers with the digits in the ones place being 1, 2, 3, 4, 5, 6, 7, 8, 9, and 0 respectively, and print them out.

  This problem is solved using arrays. Array a[100] is used to store the 100 random integers generated, and array x[10] is used to store the number of numbers whose ones digit is 1, 2, 3, 4, 5, 6, 7, 8, 9, and 0. That is, the number of numbers whose ones digit is 1 is stored in x[1], the number of numbers whose ones digit is 2 is stored in x[2], and ... the number of numbers whose ones digit is 0 is stored in x[10].

void main()
{ int a[101],x[11],i,p;
for(i=0;i<=11;i++)
x=0;
for(i=1;i<=100;i++) {
a=rand() % 100;
printf("%4d",a);
if(i%10== 0) printf("n") ;
} for(i=1;i<=100;i++) { p = a%10 ; if(p==0) p = 10 ; }   2. Find the greatest common divisor and least common multiple of two integers.   Analysis: The algorithm idea for finding the greatest common divisor is: (least common multiple = product of two integers / greatest common divisor) (1) For two known numbers m and n, make m>n; (2) m divided by n has a remainder r; (3) If r=0, then n is the greatest common divisor obtained and the algorithm ends; otherwise, execute (4); (4) m←n, n←r, and repeat (2). For example: Find the greatest common divisor of m=14, n=6. mnr 14 6 2 6 2 0 void main() { int nm,r,n,m,t; printf("please input two numbers:n"); scanf("%d,%d",&m,&n); nm=n*m; if (m=k) printf("This number is prime"); else printf("This number is not prime"); } Write it as a function, if it is a prime number, it returns 1, otherwise it returns 0. int prime( m%) {int i,k; k=sqrt(m); for(i=2;i=k) return 1; else return 0; } main() { int x,i;

















































































printf("please input a even number(>=6):n");
scanf("%d",&x);
if (x<6||x%2!=0)
printf("data error!n");
else
for(i=2;i<=x/2;i++)
if (prime(i)&&prime(xi))
{
printf("%d+%dn",i,xi);
printf("Verification successful!");
break;
}
}

  V. Sorting Problems

  1. Selection sorting (ascending)

  Basic idea:
1) For a sequence of n numbers (stored in array a(n)), select the smallest number and exchange it with the first number;
2) Except for the first number, select the smallest number from the remaining n-1 numbers and exchange it with the second number;
3) And so on. After selecting n-1 times, the sequence has been arranged in ascending order.

The program code is as follows:
void main()
{ int i,j,imin,s,a[10];
printf("n input 10 numbers:n");
for(i=0;i<10;i++)
scanf("%d",&a);
for(i=0;i<9;i++)
{ imin=i;
for(j=i+1;j<10;j++)
if(a[imin]>a[j]) imin=j;
if( i!=imin)
{s=a; a=a[imin]; a[imin]=s; }
printf("%dn",a);
}
}

  2. The basic idea of ​​bubble sorting (ascending)

  : (Compare two adjacent numbers and move the smaller one to the front)
1) There are n numbers (stored in array a(n)). In the first round, compare every two adjacent numbers and move the smaller one to the front. After n-1 times of pairwise comparison, the largest number has "sunk to the bottom" and is placed at the last position, and the smaller numbers have risen and "floated";
2) In the second round, compare the remaining n-1 numbers (the largest number has "sunk to the bottom") according to the above method. After n-2 times of pairwise comparison, the next largest number is obtained;
3) And so on. The n numbers are compared in a total of n-1 rounds, and nj pairwise comparisons are performed in the jth round.
The program segment is as follows
void main()
{ int a[10];
int i,j,t;
printf("input 10 numbersn");
for(i=0;i<10;i++)
scanf("%d",&a);
printf("n");
for(j=0;j<=8;j++)
for(i=0;i<9-j;i++)
if(a>a[i+1])
{t=a;a=a[ i+1];a[i+1]=t;}
printf("the sorted numbers:n");
for(i=0;i<10;i++)
printf("%dn",a);
}

  3.

  The basic idea of ​​​​merge sorting (merge two ordered arrays A and B into another ordered array C, ascending order) :
1) First take the first element in array A and B for comparison, and put the smaller element into array C;
2) Take the next element of the array where the smaller element is located and compare it with the larger element in the other array after the last comparison, and repeat the above comparison process until one array is sorted first;
3) Copy the remaining elements of the other array into array C, and the merge sort is completed.
The program segment is as follows:
void main()
{ int a[10],b[10],c[20],i,ia,ib,ic;
printf("please input the first array:n");
for(i=0;i<10;i++)
scanf("%d",&a);
for(i=0;i<10;i++)
scanf("%d",&b);
printf("n");
ia=0;ib=0;ic =0;
while(ia<10&&ib<10)
{ if(a[ia]{ c[ic]=a[ia];ia++;}
else
{ c[ic]=b[ib];ib++;}
ic++;
}
while(ia<=9)
{ c[ic]=a[ia];
ia++;ic++;
}
while(ib<=9)
{ c[ic]=b[ib];
b++;ic++;
}
for(i=0;i<20;i++)
printf("%dn",c);
}

  VI. Search Problem

  1. ① Sequential search method (searching for a number x in a list of numbers)

  Basic idea: a list of numbers is placed in array a[1]---a[n], the number to be searched is placed in x, and x is compared with the elements in array a from beginning to end. Variable p is used to represent the index of the element in array a, and the initial value of p is 1. Compare x with a[p]. If x is not equal to a[p], p=p+1, and repeat this process. Once x is equal to a[p], exit the loop. In addition, if p is greater than the length of the array, the loop should also stop. (This process can be implemented by the following statements)
void main()
{ int a[10],p,x,i;
printf("please input the array:n");
for(i=0;i<10;i++)
scanf("%d",&a);
printf("please input the number you want find:n");
scanf("%d",&x);
printf("n");
p=0;
while(x!=a[p]&&p<10)
p++;
if(p>=10)
printf("the number is not found!n");
else
printf("the number is found the no%d!n",p);
}
Thinking: Rewrite the above program into a search function Find. If found, it returns the subscript value, otherwise it returns -1.
②Basic idea: A column of numbers is placed in the array a[1]---a[n]. The key value to be searched is key. Compare key with the elements in array a from beginning to end. If they are the same, the search is successful. If not found, the search fails. : (The search subroutine is as follows. index: stores the index of the found element.)
void main()
{ int a[10],index,x,i;
printf("please input the array:n");
for(i=0;i<10;i++)
scanf("%d",&a);
printf("please input the number you want find:n");
scanf("%d",&x);
printf("n");
index=-1;
for(i=0;i<10;i++)
if(x==a)
{ index=i; break;
}
if(index==-1)
printf("the number is not found!n");
else
printf("the number is found the no%d!n",index);
}

  2. Binary search method (can only search for ordered sequences)

  Basic idea: suppose n ordered numbers (from small to large) are stored in the array a[1]----a[n], and the number to be searched is x. The variables bot, top, and mid represent the bottom (lower bound of the array), top (upper bound of the array), and middle of the search data range, respectively. mid=(top+bot)/2. The binary search algorithm is as follows:
(1) If x=a(mid), the result has been found and the loop is exited. Otherwise, the following judgment is made.
(2) If x(3) If x>a(mid), x must fall between mid+1 and top, that is, bot=mid+1.
(4) After the new search range is determined, the above comparison is repeated until the result is found or bot<=top.
Write the above algorithm as the following program:
void main()
{
int a[10],mid,bot,top,x,i,find;
printf("please input the array:n");
for(i=0;i<10;i++)
scanf("%d",&a);
printf("please input the number you want find:n");
scanf("%d",&x);
printf("n");
bot=0;top=9;find=0 ;
while(bot{ mid=(top+bot)/2;
if(x==a[mid])
{find=1;break;}
else if(xtop=mid-1;
else
bot=mid+1;
}
if (find==1)
printf("the number is found the no%d!n",mid);
else
printf("the number is not found!n");
}

  7. Insertion method:

  Insert a number into an ordered sequence, and the sequence remains ordered after insertion.

  Basic idea: n ordered numbers (from small to large) are stored in an array a(1)-a(n), and the number x to be inserted. First, determine the position P where x is inserted in the array; (this can be achieved by the following statement)
#define N 10
void insert(int a[],int x)
{ int p, i;
p=0;
while(x>a[p]&&pp++;
for(i=N; i>p; i--)
a=a[i-1];
a[p]=x;
}
main()
{ int a[N+1]={1,3,4,7,8,11,13,18,56,78}, x, i;
for(i=0; iprintf("nInput x:");
scanf("%d", &x);
insert(a, x);
for(i=0; i<=N; i++) printf("%d,", a);
printf("n");
}

  VIII. Matrix (two-dimensional array) operations

(1) Matrix addition and subtraction operations
C(i,j)=a(i,j)+b(i,j) Addition
C(i,j)=a(i,j)-b(i,j) Subtraction
(2) Matrix multiplication
(Matrix A has M*L elements and Matrix B has L*N elements, then Matrix C=A*B has M*N elements). Any element in matrix C (i=1,2,…,m; j=1,2,…,n)
#define M 2
#define L 4
#define N 3
void mv(int a[M][L], int b[L][N], int c[M][N])
{ int i, j, k;
for(i=0; ifor(j=0; j{ c[j]=0;
for (k=0; kc[j]+=a[k]*b[k][j];
}
}
main()
{ int a[M][L]={{1,2,3,4},{1,1,1,1}};
int b[L][N]={{1,1,1},{1,2,1},{2,2,1},{2,3,1}}, c[M][N];
in t i, j;
mv(a,b,c);
for(i=0; i{ for(j=0; jprintf("%4d", c[j]);
printf("n");
}
}
(3) Matrix transposition
Example: There is a two-dimensional array a(5,5). To transpose it, the following two methods can be used:
#define N 3
void ch1(int a[N][N])
{ int i, j, t;
for(i=0; ifor(j=i+1; j{ t=a[j];
a[j]=a[j];
a[j]=t;
}
}
void ch2(int a[N][N])
{ int i, j, t;
for(i=1; ifor(j= 0; j{ t=a[j];
a[j]=a[j];
a[j]=t;
}
}
main()
{ int a[N][N]={{1,2,3},{4,5,6},{7,8,9}}, i, j;
ch1(a); /*or ch2(a);*/
for(i=0; i{ for(j=0; jprintf("%4d", a[j]);
printf("n");
}
}
(4) Find the minimum element in a two-dimensional array and its row and column
The basic idea is the same-dimensional array, which can be implemented by the following program segment (taking the two-dimensional array a[3][4] as an example):
'The variable max stores the maximum value, and row and column store the row and column numbers of the maximum value
#define N 4
#define M 3
void min(int a[M][N])
{ int min, row, column, i, j;
min=a[0][0];
row=0;
column=0;
for(i=0; ifor(j=0; jif(a[j]{ min=a[j];
row=i;
column=j;
}
printf("Min=%dnAt Row%d,Column%dn", min, row, column);
}
main()
{ int a[M][N]={{1,23,45,-5},{5,6,-7,6},{0,33,8,15}};
min(a);
}

  IX. Iteration Method

  Algorithm idea: For the solution x of a problem, a new value x1 can be obtained from a given initial value x0 according to a certain iterative formula. This new value x1 is closer to the required value x than the initial value x0. Then use the new value as the initial value, that is: x1→x0, and calculate x1 again according to the original method.Repeat this process until |x1-x0|<ε (a given precision). At this point, x1 can be used as the solution to the problem.
Example: Use the iteration method to find the square root of a number. The iteration formula for finding the square root is known to be:
#include
float fsqrt(float a)
{ float x0, x1;
x1=a/2;
do{
x0=x1;
x1=0.5*(x0+a/x0);
}while(fabs(x1-x0)>0.00001);
return(x1);
}
main()
{ float a;
scanf("%f", &a);
printf("genhao =%fn", fsqrt(a));
}

  10. Number system conversion

  Convert a decimal integer m into a →r(2-16) base string.

  Method: Divide m by r and take the remainder until the quotient is zero, and get the result in reverse order. Write a conversion function below. The parameter idec is a decimal number, and ibase is the base to be converted (such as the base of binary is 2, the base of octal is 8, etc.). The function outputs a string.
char *trdec(int idec, int ibase)
{ char strdr[20], t;
int i, idr, p=0;
while(idec!=0)
{ idr=idec % ibase;
if(idr>=10)
strdr[p++]=idr-10+65;
else
strdr[p++]=idr+48;
idec/=ibase;
}
for(i=0; i

{ t=strdr;
strdr=strdr[pi-1];
strdr[pi-1]=t;
}
strdr[p]='';
return(strdr);
}
main()
{ int x, d;
scanf("%d%d", &x, &d);
printf("%sn", trdec(x,d));
}

  11. General processing of strings

  1. Simple encryption and decryption
The idea of ​​encryption is: Add (or subtract) an ordinal number K to each letter C, that is, replace it with the Kth letter after it, the transformation formula is: c=c+k
For example, the ordinal number k is 5, then A→F, a→f, B→?G... When the letter after the ordinal number is added exceeds Z or z, then c=c+k -26
For example: You are good→ Dtz fwj ltti
Decryption is the inverse process of encryption.
Subtract (or add) an ordinal number K from each letter C, that is, c=ck.
For example, the ordinal number k is 5, then Z→U, z→u, Y→T... When the letter after the ordinal number is added is less than A or a, then c=ck +26 The
following program is the encryption processing:
#include
char *jiami(char stri[])
{ int i=0;
char strp[50],ia;
while(stri!='')
{ if(stri>='A'&&stri<='Z')
{ ia=stri+5;
if (ia>'Z') ia-=26;
}
else if(stri>='a'&&stri<='z')
{ ia=stri+5;
if (ia>'z') ia-=26;
}
else ia=stri;
strp[i++]=ia;
}
strp='';
return(strp);
}
main()
{ char s[50];
gets(s);
printf("%sn", jiami(s));
}
2. Count the words in a text
Input a line of characters and count the words in it. The words are separated by spaces.
Algorithm idea:
(1) Starting from the left side of the text (string), take a character; let the logical quantity word represent whether the character is a character in a word, and set the initial value to 0.
(2) If the character is not a word separator such as "space", "comma", "semicolon" or "exclamation mark", then determine whether word is 1. If word is not 1, it indicates the beginning of a new word. Let the word number num = num +1, and let word = 1;
(3) If the character is a word separator such as "space", "comma", "semicolon" or "exclamation mark", it indicates that the character is not a character in a word, and let word = 0;
(4) Take the next character in turn, and repeat (2) (3) until the end of the text.
The following program segment counts the number of words contained in the string string
#include "stdio.h"
main()
{char c,string[80];
int i,num=0,word=0;
gets(string);
for(i=0;(c=string)!='';i++)
if(c==' ') word=0;
else if(word==0)
{ word=1;
num++;}
printf("There are %d word in the line.n",num);
}

  12. Exhaustive method
  
  The basic idea of ​​exhaustive method (also known as "enumeration method") is to list all possible situations one by one and judge which one may be the solution that meets the requirements. This is a "method when there is no other way" and is the most "dumb" method. However, it often works for some problems that cannot be solved by analytical methods. Usually loops are used to deal with exhaustive problems.
Example: A 100-yuan RMB note is exchanged for 100 5-yuan, 1-yuan and 0.5-yuan notes of equal value. It is required that each note must be at least 1. What are the combinations?
main()
{ int i, j, k;
printf(" 5 yuan 1 yuan 5 cents n");
for(i=1; i<=20; i++)
for(j=1; j<=100-i; j++)
{ k=100-ij;
if(5*i+1*j+0.5*k==100)
printf(" %3d %3d %3dn", i, j, k);
}
}

  13. Recursive algorithm
  
  Using its own structure to describe itself is called recursion.
  
  VB allows calling itself within the definition of a Sub procedure and a Function procedure, that is, recursive Sub procedure and recursive Function function. Recursive processing is generally implemented using a stack. Each time it calls itself, the current parameter is pushed onto the stack until the recursive end condition is reached; then the current parameter is popped off the stack until the stack is empty.
Recursive conditions: (1) The recursive end condition and the value at the end; (2) It can be expressed in a recursive form, and the recursion develops towards the end condition.
Example: Write a recursive function fac(n)=n!
int fac(int n)
{ if(n==1)
return(1);
else
return(n*fac(n-1));
}
main()
{ int n;
scanf("%d", &n);
printf("n!=%dn", fac(n));
}

Reference address:Common Algorithms for C Programming

Previous article:Design of Intelligent Traffic Intersection Controller
Next article:Control Signal Processing System Based on ADSP-BF561

Latest Microcontroller Articles
Change More Related Popular Components

EEWorld
subscription
account

EEWorld
service
account

Automotive
development
circle

About Us Customer Service Contact Information Datasheet Sitemap LatestNews


Room 1530, 15th Floor, Building B, No.18 Zhongguancun Street, Haidian District, Beijing, Postal Code: 100190 China Telephone: 008610 8235 0740

Copyright © 2005-2024 EEWORLD.com.cn, Inc. All rights reserved 京ICP证060456号 京ICP备10001474号-1 电信业务审批[2006]字第258号函 京公网安备 11010802033920号