⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 mergesort.c

📁 merge sort is a sorting algorithm used for sorting data it uses divide and conquer approach
💻 C
字号:
#include<stdio.h>
#include<conio.h>

int *a , n,*result;

void display(int *a , int l,int h)
{
     int i;
     printf("\n\narray is : ");
     for(i=l;i<=h;i++)
          printf(" %d ",a[i]);
}

void merge(int low,int mid,int high)
{
     printf("\nMerge now : low : %d   mid : %d  high  : %d",low,mid,high);
     //display(a,low,mid);
     //display(a,mid+1,high);
     int i=low,j=mid+1,k , count = low;
     while(i<=mid && j <= high)
     {
          if(a[i]>a[j])
              result[count++] = a[j++];
          else
              result[count++] = a[i++];
     }
     //printf("  i= %d  j = %d",i,j);
     while(i<=mid)
     {     
           //printf("in small");
           result[count++] = a[i++];
     }
     while(j<=high)
     {     
           //printf("in large %d count = %d",a[j],count);
           result[count++] = a[j++];
     }
     //printf("\nmerged ");
     //display(result,low,high);
     for(k = low;k<=high;k++)
          a[k] = result[k];
     display(a , low,high);
     //printf("\nmerging ends\n");          
     
}

void mergesort(int low , int high)
{
      int mid;
      //display(a , low,high);
      if(low < high)
      {
             mid = (low + high)/2;
             mergesort(low,mid);
             mergesort(mid+1 , high);
             merge(low,mid,high);
      }
}

int  main()
{
        int i;
        printf("\nEnter no. of elements to sort : ");
        scanf("%d",&n);
        a = (int *)malloc(n*sizeof(int));
        result = (int *)malloc(n*sizeof(int));
        printf("\nEnter the %d elements to be sorted : ",n);
        for(i=0;i<n;i++)
             scanf("%d",&a[i]);
        
        mergesort(0,n-1);
        display(a , 0 , n-1);
        getch();
        return 0;
        
}
            

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -