> For the complete documentation index, see [llms.txt](https://codehs.gitbook.io/apjava/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://codehs.gitbook.io/apjava/algorithms-and-recursion/insertion-sort.md).

# Insertion Sort

Insertion Sort is another sorting algorithm that we can use to sort arrays. Going back to the statistics package example discussed in the previous chapter, we can use Insertion Sort to sort our array of integers so that we can find the median value.

## How it works

As with Selection Sort, Insertion Sort uses loops to iterate over the array. However, there is an important difference: while Selection Sort searches for the smallest element on each iteration, Insertion Sort immediately puts each element into its designated position as it iterates over the array.

!["Insertion Sort Example"](/files/-M4CF6g5eFCGoF4TCBSc)

## What it looks like

Here is an example of what an Insertion Sort algorithm looks like:

```java
// Note: In some cases the list may be sorted in reverse order.

public class InsertionSort extends ConsoleProgram
{
  public void run()
  {
    // Create our array of integers to sort
    int[] intsToSort = {1, 5, 6, 3};

    // We start at `1` instead of `0`
    // because first value is already sorted
    for(int i = 1; i < intsToSort.length; i++)
    {
      int currNum = intsToSort[i];

      // Shift element into designated position
      int currIndex = i-1;
      while(currIndex > -1 && intsToSort[currIndex] > currNum)
      {
        intsToSort[currIndex+1] = intsToSort[currIndex];
        currIndex--;
      }
      intsToSort[currIndex+1] = currNum;
    }
  }
}
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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/insertion-sort.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.
