快排算法可视化

上文: java 可视化冒泡排序

最终效果

快排算法可视化

在上面基础上 在Main类中添加一下快速排序的代码

public class MainVisualSort {

    private boolean needSwap(int i, int j) {
        return i < j;
    }

    public void bubbleSort(List<Integer> list) {

        for (int i = 0; i < list.size(); i++) {
            for (int j = i + 1; j < list.size(); j++) {
                if (needSwap(list.get(j), list.get(i))) {
                    list.set(j, list.set(i, list.get(j)));
                }
            }
        }
    }
   
   // 新增部分
    public void quickSort(List<Integer> list) {
        quickSort(list, 0, list.size() - 1);
    }

    private void quickSort(List<Integer> list, int left, int right) {
        if (right <= left || left >= list.size() || right < 0) {
            return;
        }

        int l = left;
        int r = right;
        int p = list.get(left);

        while (l < r) {

            while (r > l && list.get(r) >= p) {
                r--;
            }

            list.set(l, list.get(r));

            while (r > l && list.get(l) < p) {
                l++;
            }

            list.set(r, list.get(l));
        }

        list.set(l, p);

        quickSort(list, left, l - 1);
        quickSort(list, l + 1, right);
    }

    public static void main(String[] args) {
        MainVisualSort mainVisualSort = new MainVisualSort();

       VisualArray visualArray = new VisualArray();

        try{
            Thread.sleep(200);
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<Integer> toDeal = new ArrayList<>();
        for (int i = 0; i < 40; i++) {
            toDeal.add(Math.abs(new Random().nextInt(71)) + 30);
        }
        List<Integer> list = new MyArray<>(Collections.singletonList(visualArray), toDeal);
        //mainVisualSort.bubbleSort(list);
        mainVisualSort.quickSort(list);
    }
}
上一篇:Java快速排序


下一篇:leetcode刷题--912. 排序数组