排序算法

2018-07-08  本文已影响1人  细雨蒙情

1、插入排序

public static int[] insertSort(int[] array) {
        int length = array.length;
        int j = 0;
        for(int i = 1; i < length; i++) {
            int temp = array[i];
            for(j = i; j > 0; j--) {
                if(temp < array[j-1]) {
                    array[j] = array[j-1];
                }else {
                    break;
                }
            }
            array[j] = temp;
        }
        return array;       
    }

2、冒泡排序

public static int[] bubbleSort(int[] array) {
        int length = array.length;
        for(int i = 0; i < length; i++ ) {
            for(int j = 1; j < length - i; j++) {
                if(array[j] < array[j -1]) {
                    int temp = array[j];
                    array[j] = array[j-1];
                    array[j-1] = temp;
                }
            }
        }
        return array;
        
    } 

3、快速排序

public static void quickSort2(int[] a,int low,int high) {
        if(low >= high) {
            return ;
        }       
        int i = low;
        int j = high;
        int temp = a[low];
        
        while(i < j) {
            //先从右边开始,找到第一个比temp小的数,注意是a[j] >= temp
            while(i < j && a[j] >= temp) j--;
            while(i < j && a[i] <= temp) i++;
            if(i < j) {
                //交换位置
                int temp1 = a[i];
                a[i] = a[j];
                a[j] = temp1;       
            }
        }
        //基准数归位
        a[low] = a[i];
        a[i] = temp;
        
        quickSort2(a,low,i-1);
        quickSort2(a,j+1,high);
    }

4、堆排序

https://www.cnblogs.com/chengxiao/p/6129630.html

5、归并排序

https://www.cnblogs.com/chengxiao/p/6194356.html

上一篇 下一篇

猜你喜欢

热点阅读