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

原来一直都是在用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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值