- package com.algorithm.sorting;
- import com.algorithm.utils.Compare;
- /*
- * Select sortting
- * time: O(N*N)
- */
- public class Selection<E> {
- Compare compare = new Compare();
- // ascending 升序排序
- public void sort(E[] list) {
- int len = list.length;
- int index = 0;
- E temp;
- for (int i = len - 1; i > 0; i--) {
- index = i;
- for (int k = 0; k < i; k++)
- if (compare.compare(list[index], list[k]) < 0)
- index = k;// get the index then swap them
- temp = list[i];
- list[i] = list[index];
- list[index] = temp;
- }
- }
- // descending降序
- public void sort(E[] list, String desc) {
- int len = list.length;
- int index = 0;
- E temp;
- for (int i = 0; i < len; i++) {
- index = i;
- for (int k = i + 1; k < len; k++)
- if (compare.compare(list[index], list[k]) < 0)
- index = k;// get the index then swap them
- temp = list[i];
- list[i] = list[index];
- list[index] = temp;
- }
- }
- }
- //该片段来自于http://www.codesnippet.cn/detail/090120148474.html
来源: http://www.codesnippet.cn/detail/090120148474.html