×

Merge and Merge sort with example in C

Assume we have two ordered Integer arrays, a[] and b[]. If we wish to combine them into another ordered array, such as c[], we can use the following straightforward technique.

  • Compare a[0] and b[0] first. Put whichever is smaller in c[0], say b[0].
  • Compare and contrast a[0] with b[1]. Put whichever of the two is smaller, say b [1,] into c[1].
  • Compare and contrast a [0] with b[2], put whichever is smaller, such as a [0], into c[2].
  • Compare a [1] with b[2] and so on. One of the arrays a[] or b[] will eventually be exhausted.
  • The remaining elements in the other array are simply copied into c[] at this point.

In file mergesort.h

#include <assert.h>
 #include <stdio.h>
 #include <stdlib.h>
void merge ( int a [ ], int b [ ], int c [ ], int m, int n ) ; 
void mergesort( int key [ ], int n )  ;
void wrt( int key [ ], int sz ) ;
in file merge.c
/ * merge a [ ] of size m\n and b [ ] of size n into c [ ] * /
# include “mergesort.h”
void merge ( int a [ ], int b [ ], int c [ ], int m, int n )
{
	int i = 0, j = 0, k = 0 ;
	while ( i< m && j < n )
		if ( a [ i ] < b [ j ] ) 
			c [ k  + + ] = a [ i + + ] ;
		else
			c [ k  + + ] = b [ j + + ] ;
	while ( i< m )
		c [ k  + + ] = a [ i + + ] ;
	while ( j< n )
		c [ k  + + ] = a [ j + + ] ;
}

It is expected that the array c [ ] has adequate area to accommodate both a [ ] and b[ ]. The programmer must ensure that the c[] boundaries are not exceeded. It's worth noting that one or both of the last two while statements, which are intended to gather up any remaining values, are not performed. This is due to the fact that at least one of the two criteria i< m and j< n will be false.

Next, we'll create a mergesort() method that calls merge(). A merge sort is far more efficient than a bubble sort. Our mergesort() function will operate on an array key[, which has a size of a power of two. The "power of two" condition will simplify the explanation. Let's pretend key [] has the following 16 numbers:

4316755804-53774291-1

The data will be processed by the algorithm in several stages. The table below depicts how we want the data to be appeared after each pass:

Unordered data
4316755804-53774291-1
First pass
3416785504-5374729-11
Second pass
1346704855-54737-1129
Third pass
0134485567-5-11247937
Fourth pass
-5-101123444789375567

We want each succeeding pair of integers to be in order after the first pass. We want each succeeding quartet of integers to be in order after the second pass. We want each subsequent octet of Integers to be in order on the third pass. Finally, we want all 16 integers to be in order after the fourth run. Merge() is used at each stage to get the desired ordering. After the third iteration, for example, we have two sub-arrays.

0    1     3     4     4     8     55     67      and      -5     -1     1     2     4     7     9     37

Both of which are correct. We get the totally sorted array in the last line of the table by combining these two subarrays. Surprisingly, the code that does this is rather quick, demonstrating the power of pointer arithmetic.

In file mergesort.c
/ * mergesort : using merge ( ) for sorting an array if size n. * / 
#include "mergesort.h"
void mergesort (int keyl], int n)
{
Int J, K, m, * w ;
for ( m = 1 ; m < n ; m * =  2 ) 		/ * m is a power of 2 * /
if ( n< m ) {
print( " ERROR: Array size not a power of 2 – end !  \n " ) ;
exit ( 1 ) ;
	}
w= calloc( n, sizeof ( int ) ) ;			/ * allocate workspace * /
assert ( w 1 = NULL ) ;			/ * check that calloc ( ) worked * /
for ( k = 1 ; k < n ; K * = 2 ) {
for ( j = 0 ; j < n – K ; i + =  2 * k )
/ *
/ / Merge two subarrays of key [ ] into a subarray of w [ ].
* /
Merge ( key + j , key + j + k, W + J, k, k ) ;
for ( i = 0; j < n ; + + j )
key [ j ] = w [ j ] ;				/ * write w back into key * /
}
free(w);					/ *  free the workspace * /
}

Related Topics

Continue in C

C language: C language is a procedure oriented programming language. We can say that it is a platform dependent language. C language is introduced by Dennis Ritchie in the year 1970. We...

2 minutes read.

Prime Number Program in C using for Loop

In this article, we will know about the procedure of checking whether a natural number inputted by the user is a prime number or non-prime number. Definition of the prime number A...

3 minutes read.

Round Robin Scheduling in C

Round Robin Scheduling in C Round robin is a CPU (Central Processing Unit) scheduling algorithm designed to share the time systems. It is one of the simplest and easiest scheduling algorithms...

4 minutes read.

What are linker and loader in C

Linker and loader are utility programs that have a significant role in executing a program. Linker: A linker is a program that joins the object files produced by the assembler/ compiler...

3 minutes read.

7 Best IDEs for C/C++ Developers in 2024

As we all know that in programming languages, C is known as the building block which cannot be contradicted, and C++ is the prolong kind of C and it can...

4 minutes read.

GPA Calculator in C

GPA stands for Grade Point Average. This GPA is used to measure the student's academic performance in educational institutes. By using this, segregation takes place and lets us know how...

4 minutes read.

C Program for Extended Euclidean algorithms

The Euclidean method simply computes the GCD (greatest common divisor) of two numbers, p and q. (Let's assume) The GCD of two integers is the greatest number that divides them both....

3 minutes read.

Compilation Process in C language

What is the Compilation Process?  The compilation is a method whereby the source code is converted into object code. It is achieved with compiler assistance. The compiler tests the source code for syntactic...

3 minutes read.

Distance Vector Routing Protocol Program in c

A distance-vector routing protocol is one of the foremost instructions of routing protocols in pc conversation principle for packet-switched networks. The hyperlink-nation protocol is the alternative foremost class.The Bellman-Ford set...

4 minutes read.

Long int in C

We use data type to avoid the type of data to be stored for a variable at the time of declaration.So, we can say that the variable type is known...

3 minutes read.

Variables in C

A variable can be defined as a name allocated to a storage space that can be manipulated by our programs. Every variable in C arbitrates about the overall layout and...

5 minutes read.

Array Example in C

An array is a collection of similar types of data elements arranged in such a way that any number of values can be assigned to it. It can store values that...

4 minutes read.

Integer Promotions in C

As we know that some of the data types such as char, short int, Enum takes a smaller number of bytes than compared to int. When an operation is applied...

3 minutes read.

Conio.h in C

Header files are the source files with the extension of .h. In c language header files are referred to as the helping files and they contain definitions of various functions...

4 minutes read.

Type qualifiers in C

Type qualifiers in C: In the C programming language, type qualifiers are the keywords that prepend to the variables to change their accessibility, i.e., we can tell that the type...

4 minutes read.

Return array from function in C

Return array from function in C C programming does not require the return to a function of a whole array as an argument. However, you can return a pointer to an array without...

2 minutes read.

Pointer arithmetic in C

In the C programming language, a pointer is an address which stores a numeric value. Hence, a developer can perform several arithmetic operations on the same just as one does...

4 minutes read.

Doubly Linked list in C

To know the Doubly Linked List in C, first we should know about how the Linked List works. Linked List The Linked list is the linear data structure. In the Linked...

5 minutes read.

How to use floor() function in C

Introduction: The floor() used as a function in the C programming language. This function uses to return the largest or most significant integer value. The integer value is smaller than...

3 minutes read.

File Operations in C

Why do I need the file? All data will be lost when the program exits. Saving data to a file keeps it safe even if the program stops working. If there...

6 minutes read.