New Android apps UniqueKey

Thursday, 28 August 2014

MERGE SORT


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#include<stdio.h>

void mergesort ( int [] , int , int );
void merge ( int [] , int , int , int );

main()
{
 int a[50] , n , i , j , first , last , mid ;
 
 printf ("enter the number of elements\n");
 scanf ("%d",&n);
 
 printf ("enter all elements\n");

 for ( i = 0 ; i < n ; i++)
 scanf ("%d",&a[ i ] );
 
 mergesort ( a , 0 , n-1 );

 printf ("the sorted array is ..\n");

 for ( i = 0 ; i < n ; i++ )
   printf ("%d\n", a[ i ] );
}

void mergesort ( int a[50] , int first , int last )
{
  int mid , i ;

  if ( first < last )
  {
   mid = ( first + last ) / 2 ;
   mergesort ( a , first , mid ) ;
   mergesort ( a , mid+1 , last );
   merge ( a , first , mid , last );
  }
}

void merge ( int a[50] , int first , int mid , int last )
{
  int temp[50] , k , i , j ;
 
  k = first ;
  i = first ;
  j = mid+1 ;
 
  while ( i < = mid && j < = last )
  {
    if ( a [ i ] < a [ j ] )
    {
     temp[k] = a[i];
     k++;
     i++;
    }
   else
   {
     temp[k] = a[j];
     k++;
     j++;
   }
  }
  while ( i < = mid ) 
  {
    temp[k] = a[i];
    k++;
    i++;
  }
  while ( j < = last )
  {
    temp[k] = a[j];
    k++;
    j++;
  }

  for ( i = first ; i < = last ; i++ )
  {
     a[ i ] = temp[ i ] ;
  }
}

No comments:

Post a Comment