算法复习——风骚的快速排序

来源:互联网 发布:java获取时间毫秒数 编辑:程序博客网 时间:2024/06/05 08:46

原来一直都是在用c++实现递归的快速排序,本着更好更快学习java的思路,用java实现快速排序的非递归形式

import java.util.LinkedList;import java.util.Scanner;/** * Created by mac on 16/5/4. */public class quick {    public static void main(String[] argc){        Scanner in = new Scanner(System.in);        int n = in.nextInt();//数组项的数量        quick qu = new quick();        qu.sort(n);    }    public void sort(int n){        int[] sum = new int[n+1];        LinkedList<node> stack  = new LinkedList<node>();//模拟栈的实现        Scanner in = new Scanner(System.in);        node noDe;        for (int i = 0; i < n; i++){            sum[i] = in.nextInt();//读入每一项        }        stack.add(new node(0,n-1));        while (!stack.isEmpty()) {            noDe = stack.removeLast();            int i,j,a,b;            i = a = noDe.getFirst();//当前排列的首部            j = b = noDe.getLast();//当前排列的尾部            int t = sum[(int)(Math.random()*(b-a+1)+a)];            int swap;            while(a <= b){                while (a <= b && sum[a] < t) a++;                while (a <= b && sum[b] > t) b--;                if (a <= b){                    swap = sum[a];                    sum[a] = sum[b];                    sum[b] = swap;                    a++;b--;                }            }            if (a<j) stack.add(new node(a,j));            if (i<b) stack.add(new node(i,b));        }        for (int i = 0; i < n; i++){            System.out.println(sum[i]);        }    }    public class node {        public node(int i,int j){            this.first = i;            this.last = j;        }        public int getFirst(){            return this.first;        }        public int getLast(){            return this.last;        }        private int first,last;    }}
GET到的点:快排的非递归java实现  LinkedList的使用,java中实现随机数的三种方式(Math.random()已经用了)

Random ra =new Random();

for (int i=0;i<30;i++)

System.out.println(ra.nextInt(10)+1);


java的数组真tm好用

0 0