> For the complete documentation index, see [llms.txt](https://algorithm.prettylog.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://algorithm.prettylog.com/algorithm-problems/algoexpert/easy/insertion-sort.md).

# Insertion Sort

<figure><img src="/files/pkKUE6i8Ucxv8ZjTeCxz" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/j49c1YlW65k1hUs91enm" alt=""><figcaption></figcaption></figure>

* best: N, 1
* average, worst: N^2, 1
* swap last

```jsx
function insertionSort(arr) {
	for (let i = 1; i < arr.length; i++) {
		const curr = arr[i];
		let idx = i;
		while (idx >= 1) {
			if (curr >= arr[idx - 1]) break; // vale at curr i, has to be compared with all previous values
			arr[idx] = arr[idx - 1]; // move backward by 1 step
			idx--;
		}
		arr[idx] = curr;
	}

	return arr;
}

function swap(arr, a, b) {
	[arr[b], arr[a]] = [arr[a], arr[b]];
}
// Do not edit the line below.
exports.insertionSort = insertionSort;
```

* swap every time

```jsx
function insertionSort(arr) {
	for (let i = 1; i < arr.length; i++) {
		const curr = arr[i];
		let idx = i;
		while (idx >= 1) {
			if (curr >= arr[idx - 1]) break; // vale at curr i, has to be compared with all previous values
			swap(arr, idx, idx - 1);
			idx--;
		}
	}

	return arr;
}

function swap(arr, a, b) {
	[arr[b], arr[a]] = [arr[a], arr[b]];
}
// Do not edit the line below.
exports.insertionSort = insertionSort;
```

* simple

```jsx
function insertionSort(arr) {
  
  for (let i = 1; i < arr.length; i++) {
    // const base = arr[i];
    let idx = i;
    while (idx > 0) {
      if (arr[idx - 1] <= arr[idx]) break;
      [arr[idx - 1], arr[idx]] = [arr[idx], arr[idx - 1]];
      idx--;
    }
    
  }
  
  return arr;
}

// Do not edit the line below.
exports.insertionSort = insertionSort;
```


---

# 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://algorithm.prettylog.com/algorithm-problems/algoexpert/easy/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.
