# Selection Sort

The second sorting method we used is called **Selection Sort**.

## Completed Code

```javascript
function selectionSort(arr) {
  var minIdx, temp,
    len = arr.length;
  for (var i = 0; i < len; i++) {
    minIdx = i;
    for (var j = i + 1; j < len; j++) {
      if (arr[j] < arr[minIdx]) {
        minIdx = j;
      }
    }
    temp = arr[i];
    arr[i] = arr[minIdx];
    arr[minIdx] = temp;

  }
  return arr;

}
console.log(selectionSort([207, 150, 71, -25, 369, 246, -13, 22, 150]));
```

## Explanation

1. `selectionSort()` searches for the element with the **lowest value**.
2. The lowest value is **-25** with an index of **3**. &#x20;
3. -25 swaps places with the first element in the array **207**. This way we now have the lowest value starting off our array.
4. Repeat the process, finding the next smallest value and putting it to the right of **-25**.
5. Repeat the process until the array is properly sorted.

## Variables Explanation

* `minIdx` - the index of our smallest value. It is initially set to the first element in our array.
* `temp` - a temporary variable to easily allow the value of `arr[minIdx]` to change.
* `i` and `j` - the indexes of the elements that are being compared.  &#x20;


---

# 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://eleven-fifty-academy.gitbook.io/javascript-152-objects-arrays/05-arrays/solutions/sorting/selection-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.
