最近剛上班,,在公司每天除了學(xué)習(xí)業(yè)務(wù)以外就是打打醬油,,利用空余時間整理了幾個排序算法 -
-
-
-
-
-
-
- public abstract class BaseSorter<E extends Comparable<E>> {
-
- public abstract void sort(E[] array,int from,int len);
-
- public final void sort(E[] array){
- sort(array,0,array.length);
- }
-
- protected final void swap(E[] array,int from,int to){
- E temp = array[from];
- array[from] = array[to];
- array[to] = temp;
- }
- }
-
-
-
-
-
-
-
-
-
-
- public class InsertSorter<E extends Comparable<E>> extends BaseSorter<E>{
-
-
- public static boolean SORT_TYPE = false;
-
- @Override
- public void sort(E[] array, int from, int len) {
- E tmp=null;
- for(int i=from+1;i<from+len;i++){
- tmp=array[i];
- int j=i;
- for(;j>from;j--){
- if(SORT_TYPE){
- if(tmp.compareTo(array[j-1])<0){
- array[j]=array[j-1];
- }else break;
- }else{
- if(tmp.compareTo(array[j-1])>0){
- array[j]=array[j-1];
- }else break;
- }
- }
- array[j]=tmp;
- }
-
-
-
-
-
- }
-
- public static void main(String[] args) {
- Integer[] elem = {32, 43, 1, 3, 54, 4, 19};
- InsertSorter<Integer> insertsort = new InsertSorter<Integer>();
-
- insertsort.sort(elem);
- for (Integer integer : elem) {
- System.out.println(integer);
- }
- }
- }
-
-
-
-
-
-
-
-
-
-
-
- public class BubbleSorter<E extends Comparable<E>> extends BaseSorter<E> {
-
-
- public static boolean SORT_TYPE = false;
-
- public final void bubble_down(E[] array, int from, int len) {
- for (int i = from; i < from + len; i++) {
- for (int j = from + len - 1; j > i; j--) {
- if (array[j].compareTo(array[j - 1]) > 0) {
- swap(array, j - 1, j);
- }
- }
- }
- }
-
- public final void bubble_up(E[] array, int from, int len) {
- for (int i = from + len - 1; i >= from; i--) {
- for (int j = from; j < i; j++) {
- if (array[j].compareTo(array[j + 1]) > 0) {
- swap(array, j + 1, j );
- }
- }
- }
- }
-
- @Override
- public void sort(E[] array, int from, int len) {
- if (SORT_TYPE) {
- bubble_up(array, from, len);
- } else {
- bubble_down(array, from, len);
- }
- }
-
- public static void main(String[] args) {
- Integer[] elem = {32, 43, 1, 3, 54, 4, 19};
- BubbleSorter<Integer> bsort = new BubbleSorter<Integer>();
-
-
-
- bsort.sort(elem, 0, elem.length);
- for (Integer integer : elem) {
- System.out.println(integer);
- }
- }
-
- }
-
-
-
-
-
-
-
-
-
-
- public class SelectSorter<E extends Comparable<E>> extends BaseSorter<E> {
-
- @Override
- public void sort(E[] array, int from, int len) {
- for (int i = 0; i < len; i++){
- int smallest = i;
- int j = i + from;
- for(;j < from + len ; j++){
- if(array[j].compareTo(array[smallest]) < 0){
- smallest = j;
- }
- }
- swap(array,i,smallest);
- }
- }
-
- public static void main(String[] args){
- Integer[] elem = {12,20,2,5,1,25,55,15};
- SelectSorter<Integer> sort = new SelectSorter<Integer>();
- sort.sort(elem);
- for (Integer integer : elem) {
- System.out.println(integer);
- }
- }
-
- }
|