非常に使いやすい選択ソート
1909 ワード
/**
*
* @author jnotnull
*/
public class SelectionSort {
private int[] list;
public SelectionSort(int[] listToSort) {
list = listToSort;
}
public void sort() {
// For each element in the array of integers...
// (Note: the final element will not need to be considered
// because by the the time it would be considered the array
// will already be correctly sorted.)
for (int i = 0; i < list.length - 1; i++) {
// Find the index of the minimum value in the array
// starting from index i.
int min = indexOfMin(i);
// Swap the elements at location i and
// location min. This places the element
// at min into its proper location in the
// sorted array.
int tmp = list[min];
list[min] = list[i];
list[i] = tmp;
}
}
private int indexOfMin(int start) {
int minIndex = start;
for (int i = start + 1; i < list.length; i++) {
if (list[i] < list[minIndex]) {
minIndex = i;
}
}
return minIndex;
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
int[] arr = {66, 20, 22, 55, 88, 77};
SelectionSort sortObj = new SelectionSort(arr);
sortObj.sort();
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
}