Skip to content

Instantly share code, notes, and snippets.

@namkyu
Last active May 8, 2018 01:27
Show Gist options
  • Save namkyu/cc0ee5edd3d550d928ef18c697e8bde1 to your computer and use it in GitHub Desktop.
Save namkyu/cc0ee5edd3d550d928ef18c697e8bde1 to your computer and use it in GitHub Desktop.
algorithm #algorithm

selection sort

@Test
public void selectionSort() {
    int[] array = {10, 8, 99, 7, 1, 5, 88, 9};
    selection_sort(array);
    System.out.println(Arrays.toString(array));
}

private static void selection_sort(int[] input) {
    int inputLength = input.length;

    for (int i = 0; i < inputLength - 1; i++) {
        int min = i;

        // find the first, second, third, fourth... smallest value
        for (int j = i + 1; j < inputLength; j++) {
            if (input[j] < input[min]) {
                min = j;
            }
        }

        // swaps the smallest value with the position 'i'
        int temp = input[i];
        input[i] = input[min];
        input[min] = temp;
    }
}

reverse

@Test
public void reverse() {
    String str = "Reverse this string";

    int slength = str.length();
    int end = slength - 1;

    char[] buf = new char[str.length()];
    for (int i = end; i != -1; i--) {

        buf[(end) - i] = str.charAt(i);
    }

    String sOut = new String(buf);
    System.out.println(String.format("In:%s", str));
    System.out.println(String.format("Out:%s", sOut));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment