快速排序

来源:互联网 发布:杀破狼 js主唱去世 编辑:程序博客网 时间:2024/05/17 06:15

import java.util.ArrayList;
import java.util.Scanner;

public class QuikSort {
    Integer[] num;

    /*
     * public static void main(String[] args) { Scanner cin = new
     * Scanner(System.in); ArrayList<Integer> list = new ArrayList<Integer>();
     * String str = cin.next();
     * System.out.println("please enter with end close"); while
     * (!str.equals("end")) { list.add(Integer.parseInt(str)); str = cin.next();
     * }
     *
     * Object[] objects = list.toArray(); Integer[] nums = new
     * Integer[objects.length]; for (int i = 0; i < nums.length; i++) { nums[i]
     * = (Integer) objects[i]; } quikSort(nums, 0, nums.length - 1); for (int i
     * = 0; i < nums.length; i++) System.out.print("  " + nums[i]);
     *
     * }
     */

    public void putIn() {
        System.out.println("please enter with end close");
        Scanner cin = new Scanner(System.in);
        ArrayList<Integer> list = new ArrayList<Integer>();
        String str = cin.next();
        while (!str.equals("end")) {
            list.add(Integer.parseInt(str));
            str = cin.next();
        }

        Object[] objects = list.toArray();
        Integer[] nums = new Integer[objects.length];
        for (int i = 0; i < nums.length; i++) {
            nums[i] = (Integer) objects[i];
        }
        quikSort(nums, 0, nums.length - 1);
        num = nums;
        for (int i = 0; i < nums.length; i++)
            System.out.print("  ," + nums[i]);

    }

    public int[] getNum() {
        int[] re = new int[num.length];
        for (int i = 0; i < num.length; i++)
            re[i] = num[i].intValue();

        return re;

    }

    private static void quikSort(Integer[] nums, int start, int end) {
        if (end > start) {

            int i = start + 1;
            int j = end;
            while (i <= j) {
                if (nums[i].intValue() - nums[start].intValue() <= 0)
                    i++;
                else {
                    Integer temp = nums[i];
                    nums[i] = nums[j];
                    nums[j] = temp;
                    j--;
                }
            }
            Integer temp1 = nums[i - 1];
            nums[i - 1] = nums[start];
            nums[start] = temp1;
            quikSort(nums, start, i - 2);
            quikSort(nums, i, end);

        }

    }

}

原创粉丝点击