# Mergesort

Mergesort is an extremely efficient sorting algorithm, compared to selection and insertion. Mergesort utilizes recursion to achieve efficient sorting of lists.

## How it works

Mergesort uses what is known as a "Divide and Conquer" strategy. This means mergesort divides the problem into smaller parts until the array length is equal to one. Then it merges together adjacent arrays and sorts them until the whole list is sorted.

Lets see this in action:

![Mergesort Example](https://3899603656-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M4CE_DjWtTxVmIYccGI%2F-M4CEbFz20voXskDd956%2F-M4CF6rUzKgvOR1tbHlC%2FAlgorithms_and_Recursion_Mergesort_Example.gif?generation=1586139043209636\&alt=media)

Here is another example:

![Mergesort Example](https://3899603656-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M4CE_DjWtTxVmIYccGI%2F-M4CEbFz20voXskDd956%2F-M4CF6rWPKcXacLwWzwP%2FAlgorithms_Mergesort_Example2.gif?generation=1586139043313601\&alt=media)

## Mergesort in Java

Here is what mergesort looks like in Java:

```java
import java.util.Arrays;

public class MyProgram extends ConsoleProgram 
{
    public void run()
    {
        int[] array1 = {7, 9, 10, 11, 20, 50, 10, 5, 3, 1, 2};
        int[] array2 = {8, 9, 4, 2, 4, 5, 1};

        System.out.print("First array: ");
        System.out.println(Arrays.toString(array1));
        System.out.print("Second array: ");
        System.out.println(Arrays.toString(array2));
        System.out.println();

        mergeSort(array1);
        mergeSort(array2);

        System.out.println("After mergesort: ");
        System.out.print("First array sorted: ");
        System.out.println(Arrays.toString(array1));
        System.out.print("Second array sorted: ");
        System.out.println(Arrays.toString(array2));
    }

    public int[] mergeSort(int[] list)
    {
        if(list.length > 1)
        {
            int firstHalf = list.length/2;
            int secondHalf = list.length - firstHalf;
            int[] listOne = new int[firstHalf];
            int[] listTwo = new int[secondHalf];

            System.arraycopy(list, 0, listOne, 0, firstHalf);
            System.arraycopy(list, firstHalf, listTwo, 0, secondHalf);

            mergeSort(listOne);
            mergeSort(listTwo);

            merge(listOne, listTwo, list);
        }
        return list;
    }

    public void merge(int[] listOne, int[] listTwo, int[]finalList)
    {
        int indexOne = 0;
        int indexTwo = 0;

        int resultPos = 0;

        while(indexOne < listOne.length && indexTwo < listTwo.length)
        {
            if(listOne[indexOne] < listTwo[indexTwo])
            {
                finalList[resultPos] = listOne[indexOne];
                indexOne++;
            }
            else
            {
                finalList[resultPos] = listTwo[indexTwo];
                indexTwo++;
            }
            resultPos++;
        }
        System.arraycopy(listOne, indexOne, finalList, resultPos, listOne.length - indexOne);
        System.arraycopy(listTwo, indexTwo, finalList, resultPos, listTwo.length - indexTwo);
    }
}
```

Here is what this looks like in the editor:

![Mergesort Example In Editor](https://3899603656-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M4CE_DjWtTxVmIYccGI%2F-M4CEbFz20voXskDd956%2F-M4CF6rYUJL2Pc47sdxF%2FAlgorithms_Mergesort_Example.png?generation=1586139043307845\&alt=media)

## Extra Notes

It is important to know that if you utilize mergesort you will need to have extra space for temporary storage.

Mergesort is also recursive, meaning it calls upon itself.

In a more advanced setting we can observe that the runtime complexity of mergesort is `O(nlogn)`. This means that mergesort is a linear (n), and the operation occurs in `log(n)` steps.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://codehs.gitbook.io/apjava/algorithms-and-recursion/mergesort.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
