×

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

Ceil and Floor in C

In arithmetic, a rational number is a number that can be expressed as the quotient p/q of two integers. Where q is zero. The set of rational numbers includes all...

6 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.

Sizeof in C

A pointer in C is defined as a variable that stores the information of the address of another variable. A pointer can be incremented or decremented, which means we can...

4 minutes read.

Armstrong Number in C

The Armstrong number is defined as the sum of each of its digits to the power of the number base for the each given number with any given number base....

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.

Exponential() in C

Introduction: In C language, there are available many types of functions. The exponential() function is one of them. It is a mathematical function. This article describes using the pow() property to...

3 minutes read.

Math functions in C

Math functions in C: In the C programming language, the compiler allows the developer to perform mathematical operations through the header’s functions, represented by <math.h>. The <math.h> header defines various mathematical...

3 minutes read.

What is the main in C?

In the C programming language, "main" is a predefined term or function. It is the primary function in every C program and is in charge of beginning and terminating the...

6 minutes read.

How to open a C file on android mobile

A C file is a file that has a .c extension and contains code written in the C language. C is a computer programming language developed by Dennis Ritchie at...

4 minutes read.

Different ways to Declare the Variable as Constant in C

There are a wide range of ways of making the variable as steady Using const keyword: The const catchphrase permits a software engineer to inform the compiler that a specific variable should...

5 minutes read.

If else Programs in C Programming

If else Programs in C programming The if-else statement in C is based on some particular conditions to perform the operations. If and only if the given condition is valid, the operations listed in...

4 minutes read.

How to get ASCII value in C

For text data on computers and the internet, ASCII (American Standard Code for Information Interchange). It is the most widely used character encoding standard. One hundred twenty-eight alphabetic, numeric, special...

3 minutes read.

Why does sizeof(x++) not Increment x in C

Sizeof() is a much-involved operator in C or C++. It is an incorporated time unary administrator which can be utilized to figure the size of its operand. The consequence of...

5 minutes read.

Runtime vs compile time in C

In the C programming language, the often used terms in every step consist of compile time and runtime. The compile time is referred to the source code that will be...

4 minutes read.

Diffie-Hellman Algorithm in C

Background: A method of public-key encryption known as elliptic curve cryptography (ECC) is based on the algebraic structure of elliptic curves over finite fields. To ensure equal security, ECC encryption requires fewer...

4 minutes read.

Multilevel Feedback Queue Scheduling (MLFQ) CPU Scheduling

In this article, you will learn how to initialise an array to 0 in C In C, an array is declared as: char ZEROARRAY[2022]; The global scope changes at runtime to all zeros....

3 minutes read.

How to Avoid Structure Padding in C

Generally, when an object of some structure type is declared, some contiguous memory will be allocated in block form, which will be allocated to structure members. To understand structure padding...

3 minutes read.

fopen() function in C

fopen() function, is one of the file handling functions. It is used to open the existing file and perform operations on the file. If the file does not exist, it...

3 minutes read.

Ferror() in c

Ferror():  In C, the ferror() function checks assuming there is a blunder in the given stream. The ferror() function is utilized to check for the document blunder on given stream. A return...

4 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.