Finding Minimum scalar product of two vectors in C

Finding Minimum Scalar product of two vector in C

Finding Minimum scalar product of two vectors

Here we will discuss about how  to find the minimum scalar product of two vectors (dot product).Take two array i.e. array X and array Y  and try to find the minimum scalar product of all permutations of the two arrays.

Algorithm

  • Enter the elements in array X and array Y.
  • Initialize Total = 0.
  •  array X should be in ascending order.
  • Sort it
  • array Y should be in descending order.
  • Sort array Y in descending order
  • Repeat from i = 1 to K
  • Total = total + (arrayX[i] * arrayY[i])
  • Return sum.

C Code to find Minimum scalar product of two vectors

#include<stdio.h>

int total(int X[], int K){
     int a, b;
     for (a = 0; a < K-1; a++)
            for (b = 0; b < K-a-1; b++)
               if (X[b] > X[b+1]){
                  int temp = X[b];
                  X[b] = X[b+1];
                  X[b+1] = temp;
                }
  }

int total_descending(int X[], int K){
     int a,b;
     for (a = 0; a < K; ++a){
        for (b = a + 1; b < K; ++b){
           if (X[a] < X[b]){
               int l = X[a];
               X[a] =X[b];
               X[b] = l;
            }
        }
     }
 }

 int main(){
      int K;
      scanf("%d",&K);
      int arrayX[K], arrayY[K];
      int a;
      for(a = 0; a < K ; a++){
          scanf("%d",&arrayX[a]);
       }
       for(a = 0; a < K ; a++){
          scanf("%d",&arrayY[a]);
       }

total(arrayX, K);
total_descending(arrayY, K);
int total = 0;
for(a = 0; a < K ; a++){
     total = total + (arrayX[a] * arrayY[a]);
 }
 printf("%d",total);
 return 0;

}
Input :

3 (Number of elements of the array)

1 3 5 (Array 1 elements)



2 4 1 (Array 2 elements)

 Output :

15

Comments