排序

来源:互联网 发布:淘宝上有卖大便的妈 编辑:程序博客网 时间:2024/06/03 20:26

1.冒泡排序

public class BubbleSort {    /**     *      * @Title: sortUp        * @Description: 从前往后冒泡       * @param arr     */    public static void sortUp(int arr[]) {        int temp = 0;        for(int i=0;i<arr.length - 1;i++) {            for(int j=0;j<arr.length - i - 1;j++) {                if(arr[j] < arr[j+1] ) {                    temp = arr[j];                    arr[j] = arr[j+1];                    arr[j+1] = temp;                }            }        }    }    /**     *      * @Title: sortDown        * @Description: 从上往下冒泡       * @param arr     */    public static void sortDown(int arr[]) {        int temp = 0;        for(int i=0;i<arr.length - 1;i++) {            for(int j=arr.length -1;j>i;j--) {                if(arr[j] > arr[j-1] ) {                    temp = arr[j];                    arr[j] = arr[j-1];                    arr[j-1] = temp;                }            }        }    }}

2.选择排序

public class SelectionSort {    public static void sort(int arr[]) {        int temp  = 0;        int k;        for(int i=0;i<arr.length;i++) {            k = i;            for(int j=i;j<arr.length;j++) {                if(arr[j] > arr[k]) {                    k = j;                }            }            temp = arr[i];            arr[i] = arr[k];            arr[k] = temp;        }    }}

3.插入排序

public class InsertSort {    public static void sort(int arr[]) {        int temp = 0;        for(int i=1;i<arr.length;i++) {            temp = arr[i];            int j = i;            while(j>0 && arr[j] >= temp) {                arr[j] = arr[j-1];                j--;            }            arr[j] = temp;        }    }}

4.希尔排序

/* * 希尔排序 */public class ShellSort {    /**     * 排序方法     */    public static void sort(long[] arr) {        // 初始化一个间隔        int h = 1;        // 计算最大间隔        while (h < arr.length / 3) {            h = h * 3 + 1;        }        while (h > 0) {            // 进行插入排序            long tmp = 0;            for (int i = h; i < arr.length; i++) {                tmp = arr[i];                int j = i;                while (j > h - 1 && arr[j - h] >= tmp) {                    arr[j] = arr[j - h];                    j -= h;                }                arr[j] = tmp;            }            // 减小间隔            h = (h - 1) / 3;        }    }}