java——快排、冒泡

直接贴代码

快排:

public class Test {
    private static void sort(int[] nums){
        if(nums == null || nums.length == 0){
            return;
        }
        quickSort(nums, 0, nums.length-1);
    }

    private static void quickSort(int[] nums, int start, int end) {
        int low = start;
        int high = end;
        int temp = nums[start];
        while(start<end){
            while (start<end && nums[end]>=temp){
                end--;
            }
            swap(nums, start, end);
            while(start<end && nums[start]<=temp){
                start++;
            }
            swap(nums, start, end);
        }
        if(start-1>low) {
            quickSort(nums, low, start - 1);
        }
        if(high>start+1) {
            quickSort(nums, start + 1, high);
        }
    }

    private static void swap(int[] nums, int i, int j){
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }

    public static void main(String [] args){
        int[] nums = {49,22,34, 6,22,19,3,19};
        sort(nums);
        for(int i=0;i<nums.length;i++){
            System.out.print(nums[i]+“ ”);
        }

    }
}

 冒泡:

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

猜你喜欢

转载自www.cnblogs.com/gaoquanquan/p/10454538.html