排序算法

来源:互联网 发布:nothing软件怎么样 编辑:程序博客网 时间:2024/06/04 01:37

快排

    package org.gebilaowang.crawller;import java.util.Scanner;/** * Created by xiehonghao on 16-8-10. */public class HduTest {    private static int[] numArr = new int[200];    //升序    private static void qsort(int arr[], int startIndex, int endIndex) {        int watcherNum = arr[startIndex];        int left = startIndex;        int right = endIndex;        if (endIndex < 0 || startIndex >= endIndex) {            return;        }        while (left < right) {            while (right > left) {                if (arr[right] < watcherNum) {                    break;                }                right--;            }            while (left < right) {                if (arr[left] > watcherNum) {                    break;                }                left++;            }            swap(left, right);        }        swap(startIndex, right);//注意这里是statIndex和right进行交换  防止出现3 -4 2 这种case        qsort(numArr, startIndex, left - 1);        qsort(numArr, left + 1, endIndex);    }    private static void swap(int left, int right) {        int temp = numArr[left];        numArr[left] = numArr[right];        numArr[right] = temp;    }    public static void main(String[] args) {        Scanner scanner = new Scanner(System.in);        while (scanner.hasNext()) {            int numCnt = scanner.nextInt();            for (int index = 0; index < numCnt; index++) {                numArr[index] = scanner.nextInt();            }            qsort(numArr, 0, numCnt - 1);            for (int index = 0; index < numCnt; index++) {                System.out.print(numArr[index]);                System.out.print(" ");            }        }    }}
0 0
原创粉丝点击