分享一个大牛的人工智能教程。零基础!通俗易懂!风趣幽默!希望你也加入到人工智能的队伍中来!请点击人工智能教程
package chimomo.learning.java.algorithm.sort;
import java.util.Arrays;
/**
* @author Chimomo
*
* <p>
* Basic Thought:
*
* The Selection Sort is following:
* Each round of sorting selecting the smallest or biggest element
* from the to-be-sorted sequence,
* put it at the end of already-ordered sequence,
* until all the elements of to-be-sorted sequence are sorted.
* </p>
*
* <p>
* Stability:
*
* Selection sort is not stable.
* </p>
*/
public class SelectionSort {
/**
* Selection Sort
*
* @param a The array to be sorted
*/
private static void selectionSort(int[] a) {
for (int i = 0; i < a.length - 1; i++) {
// Store the subscript of the smallest element
int min = i;
// Find the smallest element
for (int j = i + 1; j < a.length; j++) {
if (a[j] < a[min]) {
min = j;
}
}
// Put the smallest element into already-ordered sequence
int t = a[min];
a[min] = a[i];
a[i] = t;
// Print each round of sorting
System.out.println(Arrays.toString(a));
}
}
/**
* Test program
*
* @param args The arguments
*/
public static void main(String[] args) {
int[] arr = {11, 16, 22, -3, 99, 0, 16, 6, -1, 99};
System.out.println("Before selection sort:");
System.out.println(Arrays.toString(arr));
System.out.println("In selection sort:");
SelectionSort.selectionSort(arr);
System.out.println("After selection sort:");
System.out.println(Arrays.toString(arr));
}
}
/* ------ Running Results ------
Before selection sort:
[11, 16, 22, -3, 99, 0, 16, 6, -1, 99]
In selection sort:
[-3, 16, 22, 11, 99, 0, 16, 6, -1, 99]
[-3, -1, 22, 11, 99, 0, 16, 6, 16, 99]
[-3, -1, 0, 11, 99, 22, 16, 6, 16, 99]
[-3, -1, 0, 6, 99, 22, 16, 11, 16, 99]
[-3, -1, 0, 6, 11, 22, 16, 99, 16, 99]
[-3, -1, 0, 6, 11, 16, 22, 99, 16, 99]
[-3, -1, 0, 6, 11, 16, 16, 99, 22, 99]
[-3, -1, 0, 6, 11, 16, 16, 22, 99, 99]
[-3, -1, 0, 6, 11, 16, 16, 22, 99, 99]
After selection sort:
[-3, -1, 0, 6, 11, 16, 16, 22, 99, 99]
*/