常用的排序算法的 java实现

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinat_33641359/article/details/80041764


/**
 * Created by qiuyunjie on 2018/4/22.
 */
public class Demo {
    public static void main(String[] args) {
        int a[] = {3, 6, 4, 1, 2, 5, 7};
        int start = 0;
        int end = a.length - 1;
//        QuickSort(a, start, end);
//        BubbleSort(a);
        SelectSort(a);
        for (int i = 0; i < a.length; i++) {
            System.out.println(a[i]);
        }
    }

//快速排序
    public static void QuickSort(int a[], int low, int high) {
        int start = low;
        int end = high;
        int key = a[low];

        while (start < end) {
//          为什么要先走右边的(这个问题非常重要)
            while (start < end && a[end] >= key) {
                end--;
            }

            if (a[end] < key) {
                int temp = a[start];
                a[start] = a[end];
                a[end] = temp;
            }

            while (start < end && a[start] <= key) {
                start++;
            }

            if (a[start] > key) {
                int temp = a[start];
                a[start] = a[end];
                a[end] = temp;
            }
        }
//         保证 low > high
        if (low < start)
            QuickSort(a, low, start - 1);

        if (end < high)
            QuickSort(a, end + 1, high);
    }

//  冒泡排序
    public static void BubbleSort(int a[]) {
        for (int i = 0; i < a.length - 1; i++) {
            for (int j = 0; j < a.length - i - 1; j++) {
                if (a[j] > a[j + 1]) {
                    int temp = a[j];
                    a[j] = a[j + 1];
                    a[j + 1] = temp;
                }
            }
        }
    }
//  选择排序
    public static void SelectSort(int a[]) {

        for(int i = 0 ; i < a.length - 1 ; i ++) {
            int min = i ;
            for(int j = i + 1; j < a.length - 1 ; j ++){
                if(a[min] > a[j]){
                    min = j ;
                }
            }
            if(min != i ) {
                int temp = a[min];
                a[min] = a[i];
                a[i] = temp;
            }
        }

    }
}



猜你喜欢

转载自blog.csdn.net/sinat_33641359/article/details/80041764