排序_快速排序

package ds.sort;

import java.util.Arrays;
import java.util.Scanner;
/**
 * 快速排序采用的是分治法思想,选择第一个数为key
 * 第一轮将比key小的放在左边,大的都放在右边
 * 然后分别再对左右两边的子数组进行类似操作
 * @author zz
 *
 */
public class QuickSort {
    public static void quicksort(int[] a, int left, int right) {
        if (left < right) {
            int key = a[left];
            int low = left;
            int high = right;
        //    boolean flag = false;
            while (low < high) {
                while (low < high && a[high] >= key) {
                    high--;
                }
        //        if(low != high) flag = true;
                a[low] = a[high];
                while (low < high && a[low] <= key) {
                    low++;
                }
                a[high] = a[low];
            }
            a[low] = key;
            quicksort(a, left, low - 1);
            quicksort(a, low + 1, right);
        }
        System.out.println(Arrays.toString(a));
    }

    public static void quickSort(int[] a, int left, int right) {
        if(left < right) {
            int key = a[left];
            int low = left;
            int high = right;
            while(low < high) {
                while(low < high && a[high] >=key) high--;
                a[low] = a[high];
                while(low < high && a[low] <= key) low++;
                a[high] = a[low];
            }
            a[low] = key;
            quickSort(a, left, low-1);
            quickSort(a, low+1, right);
        }
        System.out.println(Arrays.toString(a));
    }
    
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("请输入数组元素的个数n: ");
        int n = input.nextInt();
        int[] a = new int[n];
        for (int i = 0; i < n; i++) {
            a[i] = input.nextInt();
        }
        quickSort(a, 0, n-1);
    }
}

 

posted @ 2017-05-23 20:08  55329  阅读(164)  评论(0编辑  收藏  举报