Chapter 7 of Robert lafore, Java data structures and algorithms

Source: Internet
Author: User

Chapter 7 of Robert lafore, Java data structures and algorithms

/* 7.1 modify the partition. Java program (List 7.2) so that the partitionit () method always uses an array (rightmost) data item with the maximum downmarked value as the pivot, rather than any data item. (This is similar to the quicksort. Java program in listing 7.3 .) Make sure that the program can execute an array of three or less data items. To achieve this goal, you need to add some additional statements. 7.2 modify the quicksort2.java Program (listing 7.4) to calculate the number of copies and comparisons in the sorting, and then display the total number. This program should have the same execution performance as the quick sort2 special applet, so the number of times of copying and comparing data in the reverse order is the same. (Remember that one exchange involves three copies .) (Question 7.2 is not done) 7.3 in Chapter 3rd exercise Question 3.2, the system prompts you to obtain the central value of a data set by sorting data and selecting intermediate data items. Readers may think that using quick sorting and selecting an intermediate data item is the fastest way to find the center value, but there is also a faster way. The division algorithm is used to calculate the central value without sorting all data items. To understand how it is implemented, let's assume that the pivot stops at the center of the array when data is divided. Work is done! All data items on the right of the hub are greater than (or equal to) the hub, and all data items on the left are smaller than (or equal to) the hub. Therefore, if the hub is located in the middle of the array, then it is the center value. The pivot usually does not stop at the center of the array, but you can find it by dividing groups that contain data items in the middle of the array. Assume that the array has seven data items distributed in the cells where the key words of the array are from 0 to 6. The subscript of the data item in the middle is 3. If you divide this array and stop at the position where the subscript is 4, you need to re-divide the data items whose subscript is 0 to 4 (this Division contains the data items whose subscript is 3 ), excluding data items with subscripts 5 to 6. If the pivot stops in the shard with the subscript 2, check whether the pivot is in the middle. Finally, the hub stops at the center and the program ends. This algorithm is faster because the number of Division times is less than the number of quick sorting. Extended programming job 7.1 to find the central value data item of an array. You can use a recursive call similar to quick sorting, but it is only used to drag an array of molecules, rather than sorting the entire array. This process stops when the data item of the central value is found, instead of waiting for the array to be sorted. 7.4 selection means to find the K-or K-small data item from an array. For example, you need to select a data item with a size of 7th. Finding the center value (for example, programming job 7.2) is a special case. You can use the same division process, but instead of looking for a data item at the intermediate position, you can find a data item with the specified lower mark. Modify the program in programming job 7.2 to allow you to select any specified data item. How many Arrays can your program process? 7.5 implement the base sorting algorithm described in the last section of this chapter. It should be able to process data items with different data volumes and data with different keyword digits. At the same time, you should be able to sort different bases (other than 10). However, unless the program can display different base values, otherwise, it is difficult to see the running status. */Package chap07; // partition. java // demonstrates partitioning an array // to run this program: c> JAVA partitionapp //////////////////////////////////// /// // class arraypar {private long [] thearray; // ref to array thearrayprivate int nelems; // number of data items // specify public arraypar (INT max) // constructor {thearray = new long [Max]; // create the arraynelems = 0; // No items yet} // specify public void insert (long value) // put element into Array {thearray [nelems] = value; // insert itnelems ++; // increment size} // specify public int size () // return number of items {return nelems;} // specify public void display () // displays array contents {system. out. print ("A ="); For (Int J = 0; j <nelems; j ++) // for each element, system. out. print (thearray [J] + ""); // display itsystem. out. println ("");} // -------------------------------------------------------------- public int partitionit (INT left, int right, long distance) {int leftptr = left-1; // right of first elemint rightptr = right + 1; // left of every twhile (true) {While (leftptr <Right & // find bigger itemthearray [++ leftptr] <strong); // (NOP) while (rightptr> left & // find smaller itemthearray [-- rightptr]> keys); // (NOP) if (leftptr> = rightptr) // If pointers cross, break; // partition doneelse // not crossed, soswap (leftptr, rightptr); // swap elements} // end while (true) return leftptr; // return partition} // end partitionit () // ================================================ ======================================/// programming job 7.1 Public int partitionit (INT left, int right) {int leftptr = left-1; // right of first elemint rightptr = right; // left of ordinary tlong records = thearray [right]; while (true) {While (leftptr <Right & // find bigger itemthearray [++ leftptr] <strong); // (NOP) while (rightptr> left & // find smaller itemthearray [-- rightptr]> keys); // (NOP) if (leftptr> = rightptr) // If pointers cross, break; // partition doneelse // not crossed, soswap (leftptr, rightptr); // swap elements} // end while (true) Swap (leftptr, right); Return leftptr; // return partition} // end partitionit () // ================================================ ======================================/// programming job 7.3 public int findmedian (INT left, int right) {int leftptr = left-1; // right of first elemint rightptr = right; // left of ordinary tlong records = thearray [right]; while (true) {While (leftptr <Right & // find bigger itemthearray [++ leftptr] <strong); // (NOP) while (rightptr> left & // find smaller itemthearray [-- rightptr]> keys); // (NOP) if (leftptr> = rightptr) // If pointers cross, break; // partition doneelse // not crossed, soswap (leftptr, rightptr); // swap elements} // end while (true) Swap (leftptr, right); int midindex = thearray. length/2; // The intermediate position if (leftptr = midindex) {return leftptr;} else if (leftptr> midindex) {return findmedian (left, leftptr-1 );} else {return findmedian (leftptr + 1, right );}} // ================================================ ========================================/// program job 7.3 public long median () {return thearray [findmedian (0, thearray. length-1)];} // ================================================ ======================================/// programming job 7.4 public int findindex (INT left, int right, int index) {int leftptr = left-1; // right of first elemint rightptr = right; // left of Hangzhou tlong records = thearray [right]; while (true) {While (leftptr <Right & // find bigger itemthearray [++ leftptr] <strong); // (NOP) while (rightptr> left & // find smaller itemthearray [-- rightptr]> keys); // (NOP) if (leftptr> = rightptr) // If pointers cross, break; // partition doneelse // not crossed, soswap (leftptr, rightptr); // swap elements} // end while (true) Swap (leftptr, right ); if (leftptr = index) {return leftptr;} else if (leftptr> index) {return findindex (left, leftptr-1, index );} else {return findindex (leftptr + 1, right, index );}} // ================================================ ===================================== public long findkth (int K) {If (k <1 | K> thearray. length) {return-1;} return thearray [findindex (0, thearray. length-1, k-1)];} // ================================================ ================= // ---------------------------------------------------------------------- public void swap (INT dex1, int dex2) // swap two elements {long temp; temp = thearray [dex1]; // A into tempthearray [dex1] = thearray [dex2]; // B into athearray [dex2] = temp; // temp into B} // end swap () // --------------------------------------------------------------} // end class arraypar /////////////////////////////// /// // public Class Partition {public static void main (string [] ARGs) {int maxsize = 16; // array sizearraypar arr; // reference to arrayarr = new arraypar (maxsize); // create the arrayfor (Int J = 0; j <maxsize; j ++) // fill array with {// random numberslong n = (INT) (Java. lang. math. random () * 199); arr. insert (n);} arr. display (); // display unsorted array // long records = 99; // specify value // system. out. print ("bandwidth is" + bandwidth); // int size = arr. size (); // partition array // int partdex = arr. partitionit (0, size-1, bytes); // system. out. println (", partition is at Index" + partdex); // arr. display (); // display partitioned array // ====================================== ============================/// programming job 7.1 // int size = arr. size (); // int partdex = arr. partitionit (0, size-1); // system. out. println ("pation is at Index" + partdex); // arr. display (); // ================================================ ==================/// programming job 7.3 // system. out. println ("median:" + arr. median (); // arr. display (); // ================================================ ================/// programming job 7.4system.out.println ("1st small value is: "+ arr. findkth (1); arr. display (); // ================================================ =============} // end main ()} // end class partitionapp /////////////////////////////////// /////////////////////////////

Package chap07; Class link {public long dData; // data itempublic link next; // next link in list // --------------------------------------------------------------- public link (long dd) // constructor {dData = dd;} // ----------------------------------------------------------------- public void displaylink () // display this link {system. out. print (dData + "") ;}// end class linkclass circlelist {Private Link C Urrent; private int nitems; Public circlelist () {current = NULL;} public void insert (long value) {link = new link (value); If (current = NULL) {current = link; Link. next = link;} else {link. next = current. next; current. next = link; current = link; // insert element. To move current, you need to move new element} nitems ++;} public long remove () {// list is empty, before calling remove, you should determine whether it is null long temp = current. next. dData; // Delete the next element of current if (current. next = Current) {// when there is only one element, current = NULL;} else {current. next = current. next. next;} nitems --; return temp;} public long PEEK () {// return the earliest inserted element // determine whether to return current is empty before calling. next. dData;} public link find (long value) {link temp = current; // Save the original link result = NULL; If (current = NULL) {return result ;} do {step (); // compare if (current. dData = value) {result = current; current = temp; // restore current To the original position, so that the insertion sequence will not be disrupted. Current points to the last inserted element return result;} while (current! = Temp); // current reaches the original position, and the return result is returned after the cycle ends in one week;} // move down one step public void step () {// After the step () method is called, the order will be disrupted. If (current! = NULL) {current = current. Next;} public void display () {If (current! = NULL) {link temp = current; do {step (); // The system is displayed starting from the current one. out. print (current. dData + "");} while (current! = Temp);} system. out. println () ;}public Boolean isempty () {Return Current = NULL;} public int size () {return nitems ;}} // ================================================ ===================================================/ /programming job 7.5 // base Sorting Algorithm // method 1 public class radixsort {// ================== ==========================================/// base Sorting Algorithm ==================================================================== // the process is as follows: // initial array 8 12 22 15 20 7 25 18 212 base 10 // First, sort by bit // The result is (20) (12 22 212) (15 25) (7) (8 18) // then sort by 10. // The result is (7 8) (12 212 15 18) (20 22 25) // then sort by hundred bits // The result is (7 8 12 15 18 20 22 25) 212 // sorting end // ================================================ = ========================== Private Static void radixsort (long [] array, int Radix, int distance) {// array is the array to be sorted // Radix represents the base number // distance represents the number of digits of the sort element // The number of digits greater than or equal to the maximum int lengt H = array. length; circlelist [] temp = new circlelist [Radix]; // used for saving elements for (INT x = 0; x <Radix; X ++) {// initialize the array temp [x] = new circlelist ();} int divide = 1; for (INT I = 0; I <distance; I ++) {// The focus of using the base sorting for the personal perception is the following code (Int J = 0; j <length; j ++) {// grouping int tempindex = (INT) (array [J]/divide) % Radix; temp [tempindex] by digits corresponding to each element. insert (array [J]);} int L = 0; For (int K = 0; k <temp. length; k ++) {// Copy the elements in the group to the original array while (! Temp [K]. isempty () {array [L ++] = temp [K]. remove () ;}} divide = divide * Radix ;}} public static void main (string [] ARGs) {long [] array = {3, 2, 3, 2, 5,333,455 66, 2345678, 78,990, 12,432, 56}; radixsort (array, 10, 7); For (INT I = 0; I <array. length; I ++) {system. out. print ("" + array [I]) ;}} // ================================================ ========================================================

Related Article

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.