java-四种排序算法

复习java基础的时候,顺手写的。代码比较丑……
1、直接插入排序

public static > T[] straight_insert_sorting(T []ts){
    int len = ts.length;
    T temp;
    for(int i=1; i=0){
            if(temp.compareTo(ts[j]) <= 0)
            {
                ts[j+1] = ts[j];
                j--;
            }
            else {
                ts[j+1] = temp;
                break;
            }
        }
        if(j<0) ts[0] = temp;
    }
    return ts;
}

2、希尔排序

 public static > T[]shell_sort(T[]ts){
    int len = ts.length;
    T temp;
    for(int gap = len/2;gap>0;gap/=2){
        for(int j=gap;j=0 ) && (temp.compareTo(ts[j-gap]) < 0)){
                ts[j] = ts[j-gap];
                j = j-gap;
            }
            ts[j] = temp;
        }
    }
    return ts;
}

3、简单选择排序

 public static >T[]select_sort(T[]ts){
    int len = ts.length;
    T min,temp;
    int pos;
    for (int i=0;ii) {
            temp = ts[i];
            ts[i] = ts[pos];
            ts[pos] = temp;
        }
    }
    return ts;
}

4、堆排序

  public static >T[]heap_sort(final T[]ts){

    final int len = ts.length;
    class HeapBuilder{
        public  void  build_max_heap(){
            for (int i = (len-2)/2;i>=0;i--){
                max_heap(i,len);
            }
        }

        void max_heap(int root,int len){
          //  System.out.println("root is:"+ts[root]);
            int left = 2 * root + 1;
            int right = left + 1;
            int largest = left;

            if (left > len-1) return;
            if ((right < len-1) && ts[right].compareTo(ts[largest])>0 )
                largest = right;
            if(ts[root].compareTo(ts[largest]) > 0) largest = root;

            if(ts[root].compareTo(ts[largest]) < 0) {
                T temp = ts[root];
                ts[root] = ts[largest];
                ts[largest] = temp;
                max_heap(largest,len);
            }
            
        }
    }
    HeapBuilder hb = new HeapBuilder();
    hb.build_max_heap();
    for (int i=len-1;i>=1;i--){
        /*System.out.print("\nheap:");
        for (T t:ts)
            System.out.print(t.toString()+" ");*/

        T temp = ts[i];
        ts[i] = ts[0];
        ts[0] = temp;

        if(i==1) break;

        hb.max_heap(0,i);
    }

    return ts;
}

你可能感兴趣的:(java-四种排序算法)