Java实现快速排序算法

快速排序

import java.util.*;
public class QuickSort{

    private static int getPosition(int[] dataArr, int low, int high){
        int key = dataArr[low];
        while(low < high){
            while(dataArr[high] > key && high > low) high--;
            dataArr[low] = dataArr[high];
            while(dataArr[low] < key && low < high) low++;
            dataArr[high] = dataArr[low];
        }
        dataArr[low] = key;
        return low;
    }

    private static void sort(int[] dataArr, int low, int high){
        if(low < high){
            int position = getPosition(dataArr, low, high);
            sort(dataArr, low, position - 1);
            sort(dataArr, position + 1, high);
        }
    }

    public static void main(String[] args){
        int[] dataArr = new int[args.length];
        for(int i = 0; i < args.length; i++){
            try{
                dataArr[i] = Integer.valueOf(args[i]);
            }catch(NumberFormatException e){
                System.out.println("input invalid decimal integer:" + e.getMessage());
                return;
            }

        }
        System.out.println("befort sort:" + Arrays.toString(dataArr));
        sort(dataArr, 0, dataArr.length - 1);
        System.out.println("after sort:" + Arrays.toString(dataArr));
    }
}

运行:
javac QuickSort.java
java QuickSort 49 38 65 97 76 13 27
输出:
befort sort:[49, 38, 65, 97, 76, 13, 27]
after   sort:[13, 27, 38, 49, 65, 76, 97]

你可能感兴趣的:(数据结构与算法)