WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Data Structures & Algorithms · Intermediate · question 23 of 100

Can you describe the merge sort algorithm and its time complexity?

📕 Buy this interview preparation book: 100 Data Structures & Algorithms questions & answers — PDF + EPUB for $5

Merge sort is a sorting algorithm that follows the divide-and-conquer paradigm. It works by recursively dividing the input array into smaller sub-arrays, sorting them, and then merging them back together to produce a sorted output array.

The merge sort algorithm can be summarized as follows:

Here is an example implementation of the merge sort algorithm in Java:

public static void mergeSort(int[] arr) {
    if (arr.length > 1) {
        int mid = arr.length / 2;
        int[] left = Arrays.copyOfRange(arr, 0, mid);
        int[] right = Arrays.copyOfRange(arr, mid, arr.length);
        mergeSort(left);
        mergeSort(right);
        merge(arr, left, right);
    }
}

public static void merge(int[] arr, int[] left, int[] right) {
    int i = 0, j = 0, k = 0;
    while (i < left.length && j < right.length) {
        if (left[i] < right[j]) {
            arr[k++] = left[i++];
        } else {
            arr[k++] = right[j++];
        }
    }
    while (i < left.length) {
        arr[k++] = left[i++];
    }
    while (j < right.length) {
        arr[k++] = right[j++];
    }
}

In this implementation, the mergeSort method takes an integer array as input and sorts it using the merge sort algorithm. If the length of the array is greater than 1, it splits the array into two sub-arrays and sorts them recursively using the mergeSort method. It then merges the two sorted sub-arrays using the merge method.

The merge method takes three integer arrays as input: the original array arr and the two sorted sub-arrays left and right. It compares the elements in the two sub-arrays and inserts them into the original array in sorted order.

The time complexity of the merge sort algorithm is O(n log n) in the worst case, where n is the size of the input array. This is because the algorithm divides the input array into two sub-arrays of roughly equal size log n times, and then merges them back together in linear time n times. The merge operation takes O(n) time in the worst case, and it is performed log n times, leading to an overall time complexity of O(n log n).

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Data Structures & Algorithms interview — then scores it.
📞 Practice Data Structures & Algorithms — free 15 min
📕 Buy this interview preparation book: 100 Data Structures & Algorithms questions & answers — PDF + EPUB for $5

All 100 Data Structures & Algorithms questions · All topics