Click here to Skip to main content
15,887,027 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
How do I optimize this code by using loop optimization?

What I have tried:

C++
#include<stdio.h>
#include<omp.h>

void merge(int array[],int low,int mid,int high)
{
  int temp[30];
  int i,j,k,m; 
  j=low;
  m=mid+1;
  for(i=low; j<=mid && m<=high ; i++)
  {
     if(array[j]<=array[m])
     {
         temp[i]=array[j];
         j++;
     }
     else
     {
         temp[i]=array[m];
         m++;
     }
  }
  if(j>mid)
  {
     for(k=m; k<=high; k++)
     {
         temp[i]=array[k];
         i++;
     }
  }
  else
  {
     for(k=j; k<=mid; k++)
     {
        temp[i]=array[k];
        i++;
     }
  }
  for(k=low; k<=high; k++)
     array[k]=temp[k];
}


void mergesort(int array[],int low,int high)
{
 int mid;
 if(low<high)
 {
   mid=(low+high)/2;

   #pragma omp parallel sections num_threads(2) 
    {
      #pragma omp section
        {
          mergesort(array,low,mid);
        }
      
      #pragma omp section
        {
          mergesort(array,mid+1,high);
        }
    }
   merge(array,low,mid,high);
 }
}


int main()
{
 int array[50];
 int i,size;
 printf("Enter total no. of elements:\n");
 scanf("%d",&size);
 printf("Enter %d elements:\n",size);
 for(i=0; i<size; i++)
 {
   scanf("%d",&array[i]);
 }
 mergesort(array,0,size-1);
 printf("Sorted Elements as follows:\n");
 for(i=0; i<size; i++)
    printf("%d ",array[i]);
 printf("\n");
 return 0;
}
Posted
Updated 9-May-19 21:35pm
v2
Comments
Patrice T 9-May-19 14:56pm    
What do you mean by "How do I optimize this code by using loop optimization?" ?
Can you elaborate ?
Member 14361566 9-May-19 14:59pm    
I want to combine loop optimization and OpenMP in order to reduce the execution time. But im not sure what kind of loop optimization technique that can be used. For example like loopfusion, loop interchanging, loop unrolling and etc.
Rick York 9-May-19 17:23pm    
Your temporary variable has only 30 entries. Make sure you don't try to load data into an index greater than that.

Quote:
I want to combine loop optimization and OpenMP in order to reduce the execution time. But im not sure what kind of loop optimization technique that can be used. For example like loopfusion, loop interchanging, loop unrolling and etc.

I fear there is no loop optimization in this case because each loop is in merge() and each operation must be done in sequence, the order of operation depend on data thus is inpredictable.
 
Share this answer
 
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900