> For the complete documentation index, see [llms.txt](https://clu.gitbook.io/data-structure-note/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://clu.gitbook.io/data-structure-note/2.1.1-selection-sort.md).

# 2.1.2 Selection Sort

我懶得寫了, 直接上code, 有空再補內文.

```java
package idv.carl.sorting.selectionsort;

/**
 * @author Carl Lu
 */
public class SelectionSort {

    private static void swap(int[] input, int i, int j) {
        int tmp = input[i];
        input[i] = input[j];
        input[j] = tmp;
    }

    public static int[] sortDesc(int[] input) {
        for (int i = 0; i < input.length - 1; i++) {
            for (int j = i + 1; j < input.length; j++) {
                if (input[i] < input[j]) {
                    swap(input, i, j);
                }
            }
        }
        return input;
    }

    public static int[] sortAsc(int[] input) {
        for (int i = 0; i < input.length - 1; i++) {
            for (int j = i + 1; j < input.length; j++) {
                if (input[i] > input[j]) {
                    swap(input, i, j);
                }
            }
        }
        return input;
    }

}
```

原始碼[點我](https://github.com/yotsuba1022/LeetCode/blob/master/src/main/java/idv/carl/sorting/selectionsort/SelectionSort.java)

Unit test:

```java
package idv.carl.sorting.selectionsort;

import static org.junit.Assert.assertArrayEquals;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

/**
 * @author Carl Lu
 */
public class SelectionSortTest {

    private static int[] input;
    private static int[] expectedDesc = new int[] {45, 34, 26, 13, 12, 9, 7, 3, 1, -1};
    private static int[] expectedAsc = new int[] {-1, 1, 3, 7, 9, 12, 13, 26, 34, 45};

    @Before
    public void init() {
        input = new int[] {12, 45, 1, 3, -1, 34, 13, 7, 9, 26};
    }

    @After
    public void destroy() {
        input = null;
    }

    @Test
    public void testSortDesc() {
        assertArrayEquals(expectedDesc, SelectionSort.sortDesc(input));
    }

    @Test
    public void testSortAsc() {
        assertArrayEquals(expectedAsc, SelectionSort.sortAsc(input));
    }

}
```

原始碼[點我](https://github.com/yotsuba1022/LeetCode/blob/master/src/test/java/idv/carl/sorting/selectionsort/SelectionSortTest.java)
