算法排序代码(简单排序)

1、冒泡排序

 

public class BoSort {

    /**
     * 交换
     * @param arr
     * @param a
     * @param b
     */
    public static void swap(int[] arr, int a, int b) {
        int temp = arr[a] ;
        arr[a] = arr[b];
        arr[b] = temp;
    }

    /**
     * 核心排序
     * @param arr
     */
    public static void posort(int arr[]) {
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr.length - i - 1; j++) {
                if (arr[j] > arr[j + 1]) {
                    swap(arr,j,j+1);
                }
            }
        }
    }

    /**
     * 打印输出
     * @param arr
     */
    public static void print( int arr[]) {
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i]+" ");
        }
    }
    public static void main(String[] args) {
        int arr[] = {1, 4, 7, 0, 5, 4, 9, 7,};
        posort(arr);
        print(arr);
    }
}
View Code

 

2、直接排序

 

public class DirectSort {

    public static void swap(int[] arr, int a, int b) {
        int temp = arr[a] ;
        arr[a] = arr[b];
        arr[b] = temp;
    }

    public static void Directsort(int arr[]) {
        for (int i = 0; i < arr.length-1; i++) {
            for (int j = i; j >=0; j--) {
                if (arr[j] > arr[j+1])
                {
                    swap(arr,j,j+1);
                }
            }
        }
    }

    public static void print( int arr[]) {
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i]+" ");
        }
    }
    public static void main(String[] args) {
        int arr[] = {1, 4, 7, 0, 5, 4, 9, 7,};
        Directsort(arr);
        print(arr);
    }
}
View Code

 

3、选择排序

 

public class SelectSort {
    public static void swap(int[] arr, int a, int b) {
        int temp = arr[a] ;
        arr[a] = arr[b];
        arr[b] = temp;
    }
    public static void selectSort(int arr[]) {
        for (int i = 0; i < arr.length-1; i++) {
            int min = i;
            for (int j = i; j < arr.length; j++) {
                if (arr[min] > arr [j])
                {
                    min = j;
                }
            }
            if (min != i){
                swap(arr,min,i);
            }
        }
        print(arr);
    }
    public static void print( int arr[]) {
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i]+" ");
        }
    }
    public static void main(String[] args) {
        int arr[] = {1, 4, 7, 0, 5, 4, 9, 7,};
        selectSort(arr);
    }
}
View Code

 

posted @ 2019-05-10 20:18  编程小白1024  阅读(633)  评论(0编辑  收藏  举报