資料結構&演算法筆記
  • Introduction
  • 1. Data Structure
  • 1.1 Stack
  • 1.1.1 Stack: Revert String
  • 1.1.2 Stack: Brackets Matching
  • 1.1.3 Stack: Reverse Polish Notation
  • 1.1.4 Stack: Calculattion for Reverse Polish Notation
  • 1.2 Queue
  • 1.2.1 Priority Queue
  • 1.3 Linked List
  • 1.3.1 Linked List - Reorder Function
  • 1.3.2 Ordered Linked List
  • 1.4 Tree
  • 1.4.1 Binary Search Tree
  • 1.4.2 Heap Tree
  • 1.4.3 Red-Black Tree
  • 1.4.3.1 RB Tree Insertion
  • 1.4.3.2 RB Tree Insertion Implementation
  • 1.4.3.3 RB Tree Delete
  • 1.4.3.4 RB Tree Delete Implementation
  • 1.4.4 B-Tree
  • 2. Algorithm
  • 2.1 Sort
  • 2.1.1 Bubble Sort
  • 2.1.2 Selection Sort
  • 2.1.3 Insertion Sort
  • 2.1.4 Merge Sort
  • 2.1.5 Quick Sort
  • 2.1.6 Merge Sort v.s. Quick Sort
  • 2.2 Search
  • 2.2.1 Binary Search
  • 2.3 Dynamic Programming
  • 2.3.1 Fibonacci Series
  • 2.3.2 Find Longest Common Suffix
  • X. Time Complexity Cheat Sheet
Powered by GitBook
On this page

Was this helpful?

2.1.2 Selection Sort

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

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;
    }

}

Unit test:

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));
    }

}
Previous2.1.1 Bubble SortNext2.1.3 Insertion Sort

Last updated 5 years ago

Was this helpful?

原始碼

原始碼

點我
點我