Javatpoint Logo
Javatpoint Logo

Merge sort

Merge sort is the algorithm which follows divide and conquer approach. Consider an array A of n number of elements. The algorithm processes the elements in 3 steps.

  1. If A Contains 0 or 1 elements then it is already sorted, otherwise, Divide A into two sub-array of equal number of elements.
  2. Conquer means sort the two sub-arrays recursively using the merge sort.
  3. Combine the sub-arrays to form a single final sorted array maintaining the ordering of the array.

The main idea behind merge sort is that, the short list takes less time to be sorted.

Complexity

Complexity Best case Average Case Worst Case
Time Complexity O(n log n) O(n log n) O(n log n)
Space Complexity O(n)

Example :

Consider the following array of 7 elements. Sort the array by using merge sort.


Merge sort

Algorithm

  • Step 1: [INITIALIZE] SET I = BEG, J = MID + 1, INDEX = 0
  • Step 2: Repeat while (I <= MID) AND (J<=END)
    IF ARR[I] < ARR[J]
    SET TEMP[INDEX] = ARR[I]
    SET I = I + 1
    ELSE
    SET TEMP[INDEX] = ARR[J]
    SET J = J + 1
    [END OF IF]
    SET INDEX = INDEX + 1
    [END OF LOOP]
    Step 3: [Copy the remaining
    elements of right sub-array, if
    any]
    IF I > MID
    Repeat while J <= END
    SET TEMP[INDEX] = ARR[J]
    SET INDEX = INDEX + 1, SET J = J + 1
    [END OF LOOP]
    [Copy the remaining elements of
    left sub-array, if any]
    ELSE
    Repeat while I <= MID
    SET TEMP[INDEX] = ARR[I]
    SET INDEX = INDEX + 1, SET I = I + 1
    [END OF LOOP]
    [END OF IF]
  • Step 4: [Copy the contents of TEMP back to ARR] SET K = 0
  • Step 5: Repeat while K < INDEX
    SET ARR[K] = TEMP[K]
    SET K = K + 1
    [END OF LOOP]
  • Step 6: Exit

MERGE_SORT(ARR, BEG, END)

  • Step 1: IF BEG < END
    SET MID = (BEG + END)/2
    CALL MERGE_SORT (ARR, BEG, MID)
    CALL MERGE_SORT (ARR, MID + 1, END)
    MERGE (ARR, BEG, MID, END)
    [END OF IF]
  • Step 2: END

C Program

Output:

printing the sorted elements 

7
9
10
12
23
23
34
44
78
101

Java Program

Output:

Sorted array 
23
23
23
34
45
65
67
89
90
101

C# Program

Output:

Sorted array 
23
23
23
34
45
65
67
89
90
101

Next TopicQuick Sort




Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA