java排序

1. 冒泡排序  比较相邻的元素。如果第一个比第二个大,就交换他们两个。

    //冒泡排序
    public static void bubble(int[] ints) {
        for(int i = 0; i < ints.length - 1; i++) {
            for(int j = i + 1; j < ints.length - 1 - i; j++) {
                if(ints[j] > ints[j + 1]) {
                    ints[i] = ints[i] + ints[j];
                    ints[j] = ints[i] - ints[j];
                    ints[i] = ints[i] - ints[j];
                }
            }
        }
    }

 

 

2. 快速排序

    //快速排序
    public static void quickSort(int[] ints, int leftIndex, int rightIndex) {
        //数字的左下标大于等于右下标,中止,递归出口
        if(leftIndex >= rightIndex) return;
        
        //排序的范围,下一次递归要用,所以复制一份
        int left= leftIndex;
        int right = rightIndex;
        
        //基准值,大于基准值的排右边,小于基准值的排左边。如: 5, 3, 1。基准值为3,排序后 1, 3, 5
        int midIndex = (leftIndex + rightIndex) / 2;
        int midValue = ints[midIndex];
        
        while(leftIndex <= rightIndex) {
            //从左往右找,直至找到大于或等于基准值, <= 会下标越界
            while(ints[leftIndex] < midValue) leftIndex++;
            //在右往左找,直至找到小于或等于基准值, >= 会下标越界
            while(ints[rightIndex] > midValue) rightIndex--;
            
            if(leftIndex > rightIndex) break;
            
            if(leftIndex < rightIndex) {//左右互换位置
                ints[leftIndex] = ints[leftIndex] + ints[rightIndex];
                ints[rightIndex] = ints[leftIndex] - ints[rightIndex];
                ints[leftIndex] = ints[leftIndex] - ints[rightIndex];                
            }
            leftIndex++;
            rightIndex--;
        }
        //递归
        quickSort(ints, leftIndex, right);
        quickSort(ints, left, rightIndex);
        
    }

 

3. 选择排序

    //选择排序:找到数组中最大的元素,与数组最后一位元素交换
    public static void selectSort(int[] ints) {
        for(int i = 0; i < ints.length - 1; i++) {
            int maxIndex = 0;//初始化最大值的下标
            for(int j = 1; j < ints.length - i; j++) {
                if(ints[j] > ints[maxIndex]) maxIndex = j;
            }
            int lastIndex = ints.length - 1 - i; //未排序中的最后的下标
            if(maxIndex != lastIndex) {
                ints[lastIndex] = ints[lastIndex] + ints[maxIndex];
                ints[maxIndex] = ints[lastIndex] - ints[maxIndex];
                ints[lastIndex] = ints[lastIndex] - ints[maxIndex];                    
            }
        }
    }

 

上一篇:如何建立Joomla电子商务网站


下一篇:不一样的冒泡排序,通俗易懂