快速排序和冒泡排序

排序算法面试经典题:

1.快速排序:

package cn.lyx.test;

/**
 * Created by lyx on 2018/5/21.
 */
public class QuickSort {

    public static void quickSort(int[] arr, int start, int end) {
        if (arr == null) return;
        if (start < end) {
            int mid = partition(arr, start, end);
            quickSort(arr, start, mid - 1);
            quickSort(arr, mid + 1, end);
        }
    }

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

    public static int partition(int[] arr, int start, int end) {
        int pivote = arr[start];
        while (start < end) {
            while (start < end && pivote < arr[end]) {
                end--;
            }
            swap(arr, start, end);
            while (start < end && pivote > arr[start]) {
                start++;
            }
            swap(arr, start, end);
        }
        return start;
    }

    public static void main(String[] args) {
        int[] arr = {5, 3, 4, 1, 2};
        quickSort(arr, 0, arr.length - 1);

        for (int x : arr) {
            System.out.print(x+" ");
        }
    }
    
}

2.冒泡排序:

package cn.lyx.test;

/**
 * Created by lyx on 2018/5/21.
 */
public class BubleSort {
    public static void bubleSort(int[] arr) {
        boolean isSwapped = true;
        while (isSwapped) {
            isSwapped = false;
            for (int i = 0; i < arr.length; i++) {
                for (int j = 0; j < arr.length - i - 1; j++) {
                    if (arr[j] > arr[j + 1]) {
                        int temp = arr[j];
                        arr[j] = arr[j + 1];
                        arr[j + 1] = temp;
                        isSwapped = true;
                    }
                }
            }
        }
    }

    public static void main(String[] args) {
        int[] arr = {5, 1, 3, 4, 2};
        bubleSort(arr);
        for (int x : arr) {
            System.out.print(x + " ");
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值