Algorithmsi pa2:randomized Queues and Deques randomizedqueue

Source: Internet
Author: User
Tags shuffle

Randomizedqueue has several key points:

1. Select the appropriate data structure, because you need to delete the element anywhere, Linked list does not, you must use resizing arrays.

2. Resizing's skills.

Q. How to grow array?
A. If array is full, create a new array of twice the size, and copy items.

Q. How to shrink array? A:halve size of array when array isOne-quarter Full3. Use stdrandom.shuffle correctly. To be able to achieve parallel use of iterator, the shuffle is not to wash the array itself, but to generate a disorderly order of index. Java Code:
//randomizedqueue-should be implemented using resizing arraysImportedu.princeton.cs.algs4.StdIn;ImportEdu.princeton.cs.algs4.StdOut;ImportEdu.princeton.cs.algs4.StdRandom;ImportJava.util.Iterator;Importjava.util.NoSuchElementException; Public classRandomizedqueue<item>ImplementsIterable<item> {    PrivateItem[] Q;//Array of items    Private intN//Number of elements//construct an empty randomized queue     PublicRandomizedqueue () {Q= (item[])NewObject[1]; N= 0; }        //is the queue empty?     Public BooleanIsEmpty () {returnN = = 0; }        //return The number of items on the queue     Public intsize () {returnN; }        //resize the underlying array holding the elements    Private voidResizeintcapacity) {        assertCapacity >=N; Item[] Temp= (item[])NewObject[capacity];  for(inti = 0; i < N; i++) {Temp[i]=Q[i]; } q=temp; }        //Add the Item//Throw A java.lang.NullPointerException if the client attempts to add a null item     Public voidEnqueue (item item) {if(Item = =NULL) {            Throw NewNullPointerException ("Add a null item"); }        if(N = =q.length) {Resize (2 * q.length);//double size of array if necessary} q[n+ +] = Item;//Add Item    }        /*When deleting random element can just simply switch it with the last element in array * and decrease the ARRA Y size counter.     So deletion'll take constant time. *throw a java.util.NoSuchElementException if the client attempts to sample or dequeue an item *from an empty Randomiz    Ed queue; */    //Remove and return a random item     PublicItem dequeue () {if(IsEmpty ()) {Throw NewNosuchelementexception ("No element"); }        intx =Stdrandom.uniform (N); Item Item=Q[x]; Q[X]= q[--N]; Q[n]=NULL; if(n = = Q.LENGTH/4 && n > 0) {Resize (q.length/2); }        returnitem; }        //return (but does not remove) a random item     PublicItem sample () {if(IsEmpty ()) {Throw NewNosuchelementexception ("No element"); }         intx =Stdrandom.uniform (N); returnQ[x]; }        //return an independent iterator through items in random order     PublicIterator<item>iterator () {return NewArrayiterator (); }        Private classArrayiteratorImplementsIterator<item> {         Private inti; Private int[] indexsequence;  PublicArrayiterator () {i= 0; Indexsequence=New int[N];  for(intj = 0; J < N; J + +) {Indexsequence[j]=J;         } stdrandom.shuffle (Indexsequence); }              Public BooleanHasnext () {returnI <N; }          Public voidRemove () {Throw Newunsupportedoperationexception (); }                   PublicItem Next () {if(!Hasnext ()) {                  Throw Newnosuchelementexception (); }            returnq[indexsequence[i++]]; }    }         Public Static voidMain (string[] args) {//Unit Testing        }}

Algorithmsi pa2:randomized Queues and Deques randomizedqueue

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.