Showing posts with label Algorithm. Show all posts
Showing posts with label Algorithm. Show all posts

8/8/21

Searching sorting algorithm

 DATA STRUCTURE

UNIT: - 7

Searching, Sorting and Complexity: -

 Searching

         Sequential Search

         Binary Search

Sorting

         Selection sort

         Bubble sort

         Quick sort

         Merge sort

 

Searching: -

1. Searching algorithms are designed to check for an element or retrieve an element from any data structure where it is stored.

2. Searching is the process of finding some particular element from the list.

3. The search is said to be successful or unsuccessful depending upon whether the element that is being searched is found or not.

4. In this algorithm if the element is found in the list then the process is called successful and the process returns the location of that element, otherwise the search is called unsuccessful.

5. Two popular searching methods that are widely used are: -

a. Sequential search

b. Binary search

 

Sequential Search: -

1. Sequential search is the simplest searching algorithm and also known as linear search.

2. This searching can be applied for both list of item sorted or unsorted.

3. The key which is to be searched is compared with each element of the list one by one.

4. If key is matched with the element then the search is terminated.

5. If the key is not matched with any element from the list then search is failed.

Time Complexity: -

1. The worst case performance of this algorithm is roughly proportional to n and represented as O(n).

2. The best case performance in which the first comparison returns a match it requires a single comparison and hence it is O(1).

3. The average case time depends on the probability that the key will found in the list. The average and worst case is proportional to n hence it is O(n).

Algorithm for sequential search: -

    Linear_search (Array A, value Y)

Step 1: -    for i = 1 to n; (n= number of element in array A)

Step 2: -    if A[i] = Y then go to step 4

Step 3: -    if i>n then go to step 5

Step 4: -    print element found and go to step 6

Step 5: -    print element not found

Step 6: -    Exit

Program Logic: -

        linear_Search(list, value)

             for each item in the list

                 if match item == value

                 return the item found

             end if

        end for

end function linear_search

 

Binary Search: -

1. Binary search tree technique is very fast and efficient.

2. Binary search algorithm applied only for sorted list of element.

3. In Binary search key is compared with the middle element of the given list, if key found search got stop.

4. Binary search followed divide and conquer approach in which the give item list is divide into two half after comparing middle element.

5. If key is not found then the key is searched in two halves depending upon the result produced through the match.

 

Time Complexity: -

1. The worst case performance of this algorithm is roughly proportional to lgn and represented as O(log n).

2. The best case performance in which the first comparison returns a match it requires a single comparison and hence it is O(1).

3. The average case time depends on the probability that the key will found in the list. The average and worst case is proportional to llgn hence it is O(log n).

 

Algorithm for sequential search: -

    Binary_search (Array A, value Y)

Step 1: -    Initialize i as first index and j as last index;

Step 2: -    while i <= j;

Step 3: -    (mid= (i+j)/2)

Step 4: -    if key == arr[mid] go to step 8

Step 5: -    else, compare key with mid is it greater then mid or smaller

Step 6: -    if mid < key, j= mid-1, go to step 2

Step 7: -    else, mid > key, i=mid + 1 go to step 2

Step 8: -    print element found go to step 10

Step 9: -    print element not found

Step 10: -  exit;

Program Logic: -

         binary_Search(arr, i, j, key)

             while(i<=j)

             mid = (i+j)/2;

if (key == arr[mid])

return k; //element found

if (key < arr [mid])

j = k-1;

else

i= k+1;

end while

return -1 //element not found

    end function binary_search

         

 

 Next update will available soon..!!

THANK YOU
Regards,

Diploma students

 

 

 

 

12/7/19

Notes for computer science and engineering branch. Subject Computer programming through c language


UNIT: - 02

ALGORITHM FOR PROBLEM SOLVING

 02.01 Exchanging values of two variables.
02.02 Summation of a set of numbers.
 02.03 Reversing digits of an integer.
 02.04 GCD(Greatest Common Division) of two numbers.
 02.05 Test whether a number is prime or not.
 02.06 Organize numbers in ascending order.
 02.07 Find square root of a number.
02.08 Factorial computation.
 02.09 Fibonacci sequence.
02.10 Compute sine Series.
 02.11 Check whether a given num is Palindrome or not.
02.12 Find Square root of a quadratic equation.
 02.13 Multiplication of two matrices.

Q. What is an algorithm?
Answer: -
         Algorithm is a set step-by-step processor, which define a set of instructions to be executed in a certain order to get the desired output.
    1.   An algorithm is a set of rules for carrying out calculation.
    2.   It is a sequence of computational steps that transform the input into the output.

02.01 Exchanging values of two variables.

Step-1       START
Step-2       Declare variable a and b;
Step-3       Read value ‘a’
Step-4       Read value ‘b’
Step-5       temp=a;
Step-6       a=b;
Step-7       b=temp;
Step-8       Print the value of ‘a’ , ‘b’.
Step-9       END

PROGRAM: -

#include<stdio.h>
#include<conio.h>
void main()
{
         int a,b,temp;
         printf("Enter the value of a and b :-\n");
         scanf("%d %d",&a,&b);
         printf("Before Swapping a=%d, b=%d \n",a,b);
         temp=a;
         a=b;
         b=temp;
         printf("After swapping a=%d, b=%d",a,b);
         getch();
}







02.02 Summation of a set of numbers.(Sum of digits of given number)

Step-1       START
Step-2       Declare variable n,m,sum=0;
Step-3       read values n; n=m;
Step-4       while(n!=0)
                 {
                          rem=n%10;
                          sum= sum + rem;
                          n= n / 10;
                 }
Step-5       print sum
Step-6       STOP

PROGRAM: -
#include<stdio.h>
#include<conio.h>
void main()
{
         int n,sum=0,rem,m;
         printf("Enter a num: -");
         scanf("%d",&n);
         m=n;
         while(n != 0)
         {
                 rem = n % 10;
                 sum = sum + rem;
                 n=n / 10;
         }
         printf("Sum of %d num is %d",m,sum);
         getch();
}





02.03 Reversing digits of an integer.

Step-1       START
Step-2       Declare variable num, reverse =0;
Step-3       read values num
Step-4       if(num < 0)
                 {
                          printf (“-“);
                          num = -num;
                 }
Step-5       do
                  {
                          printf("%d", num % 10);
                          num = num / 10;
                  }
while(num !=0);
Step-6       STOP         

Note: - This algorithm is apply on both negative and positive number.

PROGRAM: -
#include<stdio.h>
#include<conio.h>
void main()
{
         long int num;
         printf("Enter  a number: -");
         scanf("%ld",&num);
         printf("Reverse of %d number is ",num);
         if(num < 0)
         {
                 printf("-");
                 num = -num;
         }
         do
         {
                 printf("%ld",num%10);
                 num=num/10;
         }while(num!=0);
        
         getch();
}



02.04 GCD(Greatest Common Division) of two numbers.(HCF- Highest Common Factor)

Step-1       START
Step-2       Declared variables num1, num2, gcd, i;
Step-3       Read values num1, num2;
Step-4       for(i=1; i <= num1 && i <= num2; ++i)
                 {
                             if(num1 % i ==0 && num2 % i==0)
                             gcd = i;
         }

Step-5       Display gcd;
Step-6       STOP

PROGRAM: - 

#include<stdio.h>
#include<conio.h>
void main()
{
    int num1, num2, i, gcd;
    printf("Enter two integers: ");
    scanf("%d %d", &num1, &num2);
    for(i=1; i <= num1 && i <= num2; ++i)
    {
        if(num1 % i ==0 && num2 % i==0)
            gcd = i;
    }
    printf("G.C.D of %d and %d is %d", num1, num2, gcd);
    getch();
}








02.05 Test whether a number is prime or not.

Step-1       START
Step-2       Declare variables num, i, prime;
Step-3       Initialize variables as
                 i <- 2
                 prime <- 1

Step-4       Take input from user as num
Step-5       Repeat the steps until i<(num/2)
Step-6       If remainder of num % i = 0
                 6.1    Prime <- 0
                         goto step 7
                 6.2    i++ or i <- i + 1
Step-7       if prime = 0
                          Display num is not a prime number.
                 else
                          Display num is a prime number.
Step-8       STOP

PROGRAM: - 

#include<stdio.h>
#include<conio.h>
int main()
{
    long int num;
         int prime=1, i=2;
    printf("Enter an integer: ");
    scanf("%ld", &num);
    while(i<(num/2))
    {
         if(num%i==0)
         prime=0;
         i++;
         }
         if(prime==0)
                 printf("Number %d is not a prime number",num);
         else
                 printf("Number %d is a prime number",num);
   
    getch();
}
 





02.06 Organize numbers in ascending order.

In this algorithm we are taking three inputs from user to arrange the input number into ascending order. For n numbers we have to go for shorting algorithm i.e selection short and merge short.

Algorithm will upload as soon as possible


PROGRAM: -

#include<stdio.h>
#include<conio.h>
int main()
{
int a[100],n,i,j,temp;
printf("enter array size [1-100] ");
scanf("%d",&n);
printf("enter %d integers ",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]); /selection sort/
for(i=0;i<=n-2;i++)
{
for(j=i+1;j<=n-1;j++)
{
if(a[i]>a[j]) /this is ascending order/
{
temp=a[i]; a[i]=a[j]; a[j]=temp;
}
}
}
printf("sorted elements ");
for(i=0;i<n;i++)
printf("%4d",a[i]);
getch();

}

02.07 Find square root of a number.

In this we are using pre-defined function sqrt() which belong to math.h header file: -

Step-1       START
Step-2       declare variable n
Step-3       read values of n from the user
Step-4       use sqrt(n)
Step-5       print <- sqrt(n);
Step-8       STOP
PROGRAM: - 

#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
             int n,m;
             printf("Enter  an integer: ");
             scanf("%d",&n);
             printf(“Square root of %d is %.2f",n,sqrt(n)); 
             getch();
}
 




02.08 Factorial computation.

Step-1       START
Step-2       Declare variables num, temp;
Step-3       declare one more variable as long fact
Step-4       initialize fact<-1
Step-5       copy num <- temp;
Step-6       while(num>=1)
                 {
                          fact=fact*num;
                          num--;
                 }
Step-7       display the factorial i.e. fact           
Step-8       STOP

PROGRAM: - 

#include<stdio.h>
#include<conio.h>
void main()
{
             int num,temp;
             long fact=1;
             printf("Enter  an integer: ");
             scanf("%d",&num);
             temp=num;
             while(num>=1)
             {
                 fact=fact*num;
                 num--;
             }
             printf("%d factorial is %d",temp,fact); 
             getch();
}






02.09 Fibonacci sequence.

Step-1       START
Step-2       Declare variables num, f1, f2, f3
Step-3       initialize f1 <- 0, f2 <- 1;
Step-4       read values of num from user
Step-5       check below condition: -
                 if(num <=0)
                 printf("Series not possible");
                 else if(num==0)
                 printf("0");
Step-6       before displaying the series display 0, 1
Step-7       the below loop is used to find the Fibonacci series
                 for(i=3; i<=num; i++)
                 {                        
                          f3=f1+f2;
                          printf(", %d",f3);
                          f1=f2;
                          f2=f3;
                 }
Step-8       STOP

PROGRAM: -

#include<stdio.h>
#include<conio.h>
void main()
{
             int num,i,f1,f2,f3;
             f1=0;
             f2=1;
             printf("Enter  an integer: ");
             scanf("%d",&num);
             if(num <=0)
             printf("Series not possible");
             else if(num==0)
             printf("0");
             else
             {
                 printf("Series is=0, 1");
                 for(i=3; i<=num; i++)
                 {
                          f3=f1+f2;
                          printf(", %d",f3);
                          f1=f2;
                          f2=f3;
                 }
             }
             getch();
 }





02.10 Compute sine Series.
Sine Series:
 Series which is used to find the value of Sin(x) is known as sine series.
In which, x is the angle in degree i.e. converted into Radian.
The following formula is used to express the value of sin(x) as sine series: -
 
Expanding the above notation, the formula of Sine Series is
For example,
 Let the value of be 30.
 
So, Radian value for 30 degree is 0.52359.
So, the value of Sin(30) is 0.5.

Step-1       START
Step-2       Declare variables i, x, sum, t
Step-3       read the values of x from the user
Step-4       Convert x value into radian
                 x=x*3.14159/180;

Step-5       initialize t <- x and sum <- x
Step-6           /* Loop to calculate the value of Sine */
                      for(i=1;i<=2;i++)
                     {
                        t=(t*(-1)*x*x)/(2*i*(2*i+1));
                       sum=sum+t;
                      }
Step-7       display the sum as sin(x) values    
Step-8       STOP

PROGRAM: -

#include<stdio.h>
#include<conio.h>
int main()
{           
    int i;
    float x, sum, t;
    printf(" Enter the value for x : ");
    scanf("%f",&x);
    x=x*3.14159/180;
    t=x;
    sum=x;
    /* Loop to calculate the value of Sine */
    for(i=1;i<=2;i++)
    {
        t=(t*(-1)*x*x)/(2*i*(2*i+1));
        sum=sum+t;
    }
    printf(" The value of Sin(%f) = %.4f",x,sum);
    getch();
}







02.11 Check whether a given num is Palindrome or not.

Step-1       START
Step-2       declares variable num, m, rev and r;      
Step-3       read values of num from the user
Step-4       initialized m <- n and rev <- 0
Step-5       while(num!=0)
                  {
                           r=num % 10;
                           rev = rev * 10 + r;
                          num = num / 10;
                  }

Step-6       if (m== rev)
                  {
                          printf("The entered integer is a palindrome");
                  }      
Step-7       else
                  {
                          printf("The entered integer is not a palindrome");
                  }

Step-8       STOP

PROGRAM: -

#include<stdio.h>
#include<conio.h>
void main()
{
         long num, m, rev=0;
         int r;
         printf("Enter an integer:");
         scanf("%d",&num);
         m=num;
         while(num!=0)
         {
                 r=num % 10;
                 rev = rev * 10 + r;
                 num = num / 10;
         }
         if (m== rev)
         {
                 printf("The %d integer is a palindrome", num);
         }    
         else
         {
                 printf("The %d integer is not a palindrome", num);
         }
         getch();
 }





02.12 Find Square root of a quadratic equation.

Step-1       START
Step-2       declare variables a, b, and c 
Step-3       read values of a, b and c
Step-4       if a =0 go to step-9
Step-5       calculate value of discriminate=b*b – 4*a*c
Step-6       From step-6 to step-8 we will find the nature of discriminate
                 if(discriminate > 0)
   {
                  root1 = (-b + sqrt(discriminate)) / (2*a);
                 root2 = (-b - sqrt(discriminate)) / (2*a);
 printf("Two distinct and real roots exists: %.2f and %.2f", root1, root2);
             }
Step-7       else if(discriminate == 0)
    {
                   root1 = root2 = -b / (2 * a);
  printf("Two equal and real roots exists: %.2f and %.2f", root1, root2);
            }

Step-8   else if(discriminate < 0)
          {
              root1 = root2 = -b / (2 * a);
                imaginary = sqrt(-discriminate) / (2 * a);

                printf("Two distinct complex roots exists: %.2f + i%.2f and %.2f i%.2f",
                root1, imaginary, root2, imaginary);
             }
Step-9   STOP

PROGRAM: -

#include <stdio.h>
#include<conio.h>
#include <math.h> /* Used for sqrt() */
int main()
{
    float a, b, c;
    float root1, root2, imaginary;
    float discriminate;
   
    printf("Enter values of a, b, c of quadratic equation (aX^2 + bX + c): ");
    scanf("%f%f%f", &a, &b, &c);
   
    /* Find discriminate of the equation */
    discriminate = (b * b) - (4 * a * c);
   
  
    /* Find the nature of discriminate */
    if(discriminate > 0)
    {
        root1 = (-b + sqrt(discriminate)) / (2*a);
        root2 = (-b - sqrt(discriminate)) / (2*a);

        printf("Two distinct and real roots exists: %.2f and %.2f", root1, root2);
    }
    else if(discriminate == 0)
    {
        root1 = root2 = -b / (2 * a);

        printf("Two equal and real roots exists: %.2f and %.2f", root1, root2);
    }
    else if(discriminate < 0)
    {
        root1 = root2 = -b / (2 * a);
        imaginary = sqrt(-discriminate) / (2 * a);

        printf("Two distinct complex roots exists: %.2f + i%.2f and %.2f - i%.2f",
                root1, imaginary, root2, imaginary);
    }

    getch();
}










02.13 Multiplication of two matrices.

Step-1       START
Step-2       declare variables a[100][100], b[100][100], nr, nc, r, c, k;
Step-3       read values of nr, nc, a[100], b[100][100] from users
Step-4       Use this for loop for performing matrix multiplication          
                      for(r=0;r<nr; r++)
                   {        
                          for(c=0;c<nc; c++)
                   {
                           int s=0;
                           for(k=0;k<nr; k++)
                   {
                           s=s+a[r][k]*b[k][c];
                   }
                           printf("%4d",s);
                   }
                          printf("\n");
                                                                   
                   }
Step-5       STOP

PROGRAM: -      

#include<stdio.h>
#include<conio.h>
int main()
{
int a[100][100], b[100][100],nr,nc,r, c, k;
printf("Enter Number of rows and columns of matrix-a and matrix-b:-");
                   scanf("%d %d",&nr,&nc);
                   printf("enter %d integers for a - matrix ", nr*nc);
                   for(r=0; r<nr; r++)
                   for(c=0; c<nc;c++)
                   scanf("%d",&a[r][c]);
                   printf("enter %d integers for b- matrix", nr*nc);
                   for(r=0; r<nr; r++)
                   for(c=0; c<nc;c++)
                   scanf("%d",&b[r][c]);
                   puts(" Multiplications of matrixes are: -");
                   for(r=0;r<nr;r++)
                   {        
                          for(c=0;c<nc;c++)
                   {
                           int s=0;
                           for(k=0;k<nr;k++)
                   {
                           s=s+a[r][k]*b[k][c];
                   }
                           printf("%4d",s);
                   }
                          printf("\n");
                                                                   
                   }
                   getch();
}


















{Other links
 COA : -















Latest Update

New Web Site

Popular Posts