+/EE422C

software design

git clone https://git.julia.blue/+/EE422C

Joseph RyanProject 1 and quiz 2ead272f

master
1.0 KiB39 linesraw
1public final class SelectionSort {
2  /**
3   * Implementation of selection sort algorithm.
4   *
5   * @param x The integer array to sort in place
6   */
7  public static void sort(int[] x) {
8    for (int i = 0; i < x.length - 1; i++) {
9
10      // Assume i is index of smallest value in array
11      int min = i;
12
13      // Check all other values in array to find smallest value
14      for (int j = i + 1; j < x.length; j++) { // FIX 1: need to check last value
15        if (x[j] < x[min]) {
16          min = j;
17        }
18      }
19
20      // Swap smallest value to its correct location
21      if (i != min) { // FIX 2: don't swap a value with itself or the xor will kill it
22        swap(x, i, min);
23      }
24    }
25  }
26
27  /**
28   * Swap two values in place using XOR algorithm.
29   *
30   * @param x The array of values
31   * @param a Index of first value in x
32   * @param b Index of second value in x
33   */
34  static void swap(int[] x, int a, int b) {
35    x[a] ^= x[b];
36    x[b] ^= x[a];
37    x[a] ^= x[b]; // FIX 3: XORing a with itself clears it
38  }
39}