Java data structures and algorithms (Robert lafore) Chapter 3
/* 3.1 bubblesort. in Java program (listing 3.1) and bubblesort special applet, The in index variable is moved from left to right until the maximum data item is found and moved out of the out variable on the right. Modify the bubblesort () method to make it bidirectional. In this way, the in index first shifts the largest data item from left to right as before. When it reaches the out variable position, it turns around and shifts the smallest data item from right to left. Two external index variables are required, one on the right (the previous out variable) and the other on the left. 3.2 In isertsort. add a median () method to the arrayins class in Java program (listing 3.3. this method returns the median of the array. (recall that half of the data items in the array are larger than the median value, and half of the data items are smaller than the median value .) 3.3 Add a method named nodups () to the insertsort. Java program (listing 3.3). This method removes duplicate data items from an array that has already been sorted without disrupting the orderliness. (You can use the insertionsort () method to sort data, or you can simply use the main () method to insert data into the table in an orderly manner .) One solution is to move a position forward from the beginning of the position to the end of the array every time a repeat data is found, which leads to a long O (n2) consumption) at least in the case of many repeated data items. In the designed algorithm, ensure that data items can be moved only once, no matter how many duplicate data items exist. In this way, the algorithm only consumes an order of magnitude O (n. 3.4 another simple sorting algorithm is parity sorting. The idea is to repeat two scans in the array. The first scan Selects all data item pairs, a [J] And a [J + 1], and J is an odd number (j =, 5 ,......). If the order of the values of their keywords is reversed, they are exchanged. The second scan performs the same operation on all even data items (j = 2, 4, 6 ,......). Repeat the sorting until the arrays are all sorted. Use the oddevensort () method to replace the bubblesort () method in the bubblesort. Java program (listing 3.1. Make sure that it can be run in the sorting of different data volumes. You also need to calculate the number of two scans. Odd-even sorting is actually very useful in multi-processor environments. The processor can simultaneously process each odd-number pair and then simultaneously process even-number pairs. Because odd pairs are independent of each other, each pair can be compared and exchanged with different processors. In this way, you can quickly sort data. 3.5 modify the insertionsort () method in the insertsort. Java program (listing 3.3) so that it can calculate the number of copies and comparisons in the sorting process and display the total number. To calculate the number of comparisons, We need to separate the two conditions of the inner while loop. This program is used to measure the number of copies and comparisons of various reverse data sorting. Does the result meet O (n2? Is it the same as having basic ordered data (with only a few unordered data? What conclusions can we draw from the performance of sorting basic ordered data on the efficiency of this algorithm? 3.6 There is an interesting way to delete the same data items in the array. Insert a nested loop algorithm to compare each data item in the array with other data items. If you want to delete the same data item, you can do so (see section 2nd of Chapter 2.6 ). Modify the insertionsort () method in insertsort. Java to delete the same data items during sorting. The method is as follows: when a duplicate data item is found, a key value smaller than any value is usually used to rewrite the same data item (if all values are positive,-1 is recommended ). As a result, the general insertion sorting algorithm will process the key value data item like other data items, and move it to the position where the subscript is 0. From now on, the algorithm can ignore this data item. The next same data item will be moved to the position where the subscript is 1, and so on. After sorting, all the same data items (now the key value is-1) are at the beginning of the array. You can change the array capacity and move the array subscript to 0 before the required data. */Package chap03; // bubblesort. java // demonstrates bubble sort // to run this program: c> JAVA bubblesortapp //////////////////////////////////// /// // class arraybub {private long []; // ref to Array Using vate int nelems; // number of data items // using public arraybub (INT max) // constructor {A = new long [Max]; // create th E arraynelems = 0; // No items yet} // optional public void insert (long value) // put element into Array {A [nelems] = value; // insert itnelems ++; // increment size} // specify public void display () // displays array contents {for (Int J = 0; j <nelems; j ++) // for each element, system. out. print ([J] + ""); // display itsystem. out. println ("") ;}// specify public void bubblesort () {int out, in; For (out = nelems-1; out> 0; out --) // outer loop (backward) // Here it must be out> 0. If it is> 1, 4321 will be arranged into limit 4for (in = 0; in <out; in ++) // inner loop (forward) if (a [in]> A [in + 1]) // out of order? Swap (in, in + 1); // swap them} // end bubblesort () // ---------------------------------------------------------------- // ======================================================= ========================================/// programming job 3.1 p78 (97) public void bubblesort1 () {int leftout = 0, rightout = nelems-1, in; // leftout, rightout is the pointer to the left and right sides for (; rightout> leftout; rightout --, leftout ++) {for (in = leftout + 1; in <rightout; In ++) if (a [in]> A [in + 1]) Swap (in, in + 1); for (in = rightout-1; in> leftout; In --) if (A [in] <A [in-1]) Swap (in, in-1 );}} // ================================================ ==========================================/// programming job 3.4 p79 (98) // The parity sorting process is as follows // The initial sequence 4 3 2 1 // 1st times // I is an even number comparison () and) // The result is 3 4 1 2 // I is an odd comparison (2nd) // The result is 3 1 4 2 // times // I is an even comparison) and () to // The result is 1 3 2 4 // I is an odd number) // The result is 1 2 3 4 // 3rd Times // I is an even number (1, 2) and (3, 4). // The result is 1. 2 3 4 // I is an odd comparison (2, 3) // The result is 1 2 3 4 // This comparison is not exchanged, so the sorting ends public void oddevensort () {Boolean change = true; while (Change) {// when there is no exchange, the order is changed = false; For (INT I = 0; I <nelems-1; I + = 2) {// I is an even number if (a [I]> A [I + 1]) {swap (I, I + 1 ); change = true ;}for (INT I = 1; I <nelems-1; I ++ = 2) {// I is an odd number if (a [I]> A [I + 1]) {swap (I, I + 1); change = true ;}}}} // ================================================ ========== ======================/// Use an independent method is not necessarily good, because method calling will increase some additional consumption. In your own program, put the code of the transaction/exchange operation directly into the program. Private void swap (INT one, int two) {long temp = A [one]; A [one] = a [two]; A [two] = temp ;} // else} // end class arraybub /////////////////////////////// /// // public class bubblesortapp {public static void main (string [] ARGs) {int maxsize = 100; // array sizearraybub arr; // reference to arrayarr = new arraybub (maxsize); // create the arrayarr. insert (77); // Insert 10 itemsarr. insert (99); arr. insert (44); arr. insert (55); arr. insert (22); arr. insert (88); arr. insert (11); arr. insert (00); arr. insert (66); arr. insert (33); arr. display (); // display itemsarr. bubblesort (); // bubble sort themarr. display (); // display them again // ======================================== =====// programming job 3.1 p78 (97) arr = new arraybub (maxsize); // create the arrayarr. insert (4); arr. insert (3); arr. insert (2); arr. insert (1); arr. display (); // display itemsarr. bubblesort1 (); // bubble sort themarr. display (); // display them again // ======================================== ======/// programming job 3.4 p79 (98) arraybub arr1 = new arraybub (maxsize); arr1.insert (8); arr1.insert (7); arr1.insert (6); arr1.insert (5); arr1.display (); arr1.oddevensort (); // parity sorting arr1.display (); // ================================================} // end main ()} // end class bubblesortapp /////////////////////////////////// /////////////////////////////
Package chap03; // insertsort. java // demonstrates insertion sort // to run this program: C> JAVA insertsortapp // specify class arrayins {private long [] A; // ref to array into vate int nelems; // number of data items // ---------------------------------------------------------------- public arrayins (INT max) // constructor {A = new long [Max]; // create th E arraynelems = 0; // No items yet} // optional public void insert (long value) // put element into Array {A [nelems] = value; // insert itnelems ++; // increment size} // specify public void display () // displays array contents {for (Int J = 0; j <nelems; j ++) // for each element, system. out. print ([J] + ""); // display itsystem. out. println ("") ;}// specify public void insertionsort () {int In, out; for (out = 1; out <nelems; out ++) // out is dividing line {long temp = A [out]; // remove marked itemin = out; // start shifts at outwhile (in> 0 & A [in-1]> = temp) // until one is smaller, // when a [in-1] = temp, you do not need to move it. You can change it to a [in-1]> temp {A [in] = A [in-1]; // shift item to right -- In; // go left one position} A [in] = temp; // insert marked item} // end for} // end insertionsort () // ---------------------------------------------------------------- // ======================================================= ========================================/// programming job 3.5 p79 (98) public int insertionsort1 () {int In, out; int compare = 0; // comparison times int copy = 0; // number of copies for (out = 1; out <nelems; out + +) // Out is dividing line {long temp = A [out]; // remove marked itemin = out; // start shifts at outwhile (in> 0) // until one is smaller, {if (a [in-1]> temp) {A [in] = A [in-1]; // shift item to right -- In; // go left one positioncompare ++; copy ++;} else {compare ++; break ;}} A [in] = temp; // insert marked item} // end forreturn compare + copy;} // end insertionsort () // ================================== ====================================/// Programming job 3.6 p79 (98) public void insertionsort2 () {int in, out, Count = 0; For (out = 1; out <nelems; out ++) // out is dividing line {long temp = A [out]; // remove marked itemin = out; // start shifts at outwhile (in> 0 & A [in-1]> = temp & A [in-1]! =-1) // until one is smaller, {if (a [in-1] = temp) {temp =-1; count ++ ;} A [in] = A [in-1]; // shift item to right -- In; // go left one position} A [in] = temp; // insert marked item} // end fornelems-= count; For (INT I = 0; I <nelems; I ++) {A [I] = A [I + Count]; // move the sorted element forward to the Count position} // end insertionsort () // ================================================ ====================================/// programming job 3.2 p78 (97) // The median of the array, Is the bottom in the middle of the position or in the middle of the size? Public long median () {This. insertionsort (); // first sort and then take the median value // This median value is the median value in size. return a [nelems/2];} // ================================================ ====================================/// programming job 3.3 p78 (97) // method 1 Public void nodups () {This. insertionsort (); // first sort int holenumber = 0; Final int flag =-1; // The flag is null. If the user does not enter a negative value for (INT I = 0; I <nelems; I ++) {// mark all the duplicates for (Int J = I + 1; j <nelems; j ++) {// starting from I + 1 if (a [I] = A [J] & A [J]! = Flag) {A [J] = flag; holenumber ++ ;}}int firsthole =-1; // The first vacant index for (INT I = 0; I <nelems; I ++) {if (a [I] = Flag & firsthole =-1) {// when the first vacancy is encountered, then the empty space is firstholefirsthole = I;} else if (a [I]! = Flag & firsthole! =-1) {// when a blank value exists, copy the non-null value to the firsthole position a [firsthole ++] = A [I]; // At the same time, firthole ++, the vacant space is moved back by one} nelems-= holenumber;} // method 2 Public void nodups1 () {This. insertionsort (); // first sort long nil = long. min_value; // flag bit for (INT I = 0; I <nelems-1; I ++) {if (a [I] = A [I + 1]) {A [I] = nil; // NIL is the flag, which is equivalent to-1 of the main building and uses long. min_value} int order = 0; For (INT temp = 0; temp <nelems;) {if (a [temp]! = Nil) {// This method can be used if (temp> order) {A [order] = A [temp];} because a [0] cannot be equal to nil. temp ++; Order ++;} elsetemp ++;} nelems = order ;} // ================================================ ===============================} // end class arrayins ///////////// //////////////////////////////////////// //// // public class insertsortapp {public static void main (string [] ARGs) {int maxsize = 100; // array sizearrayins arr; // reference to arrayarr = new arrayins (maxsize); // create the arrayarr. insert (77); // Insert 10 itemsarr. insert (99); arr. insert (44); arr. insert (55); arr. insert (22); arr. insert (88); arr. insert (11); arr. insert (00); arr. insert (66); arr. insert (33); arr. display (); // display itemsarr. insertionsort (); // Insertion-Sort themarr. display (); // display them again // ======================================== ======/// insert 4321arr = new arrayins (maxsize ); // create the arrayarr. insert (4); arr. insert (3); arr. insert (2); arr. insert (1); arr. display (); // display itemsarr. insertionsort (); // Insertion-Sort themarr. display (); // display them again // ======================================== =====// programming job 3.3 p78 (97) arr = new arrayins (maxsize); // create the arrayarr. insert (2); arr. insert (3); arr. insert (4); arr. insert (3); arr. insert (3); arr. insert (1); arr. insert (2); arr. insert (1); arr. insert (1); arr. insert (1); system. out. println ("after repeated values are inserted:"); arr. display (); arr. nodups (); system. out. println ("after the duplicate value is deleted:"); arr. display (); // ================================================ // programming job 3.5 p79 (98) arr = new arrayins (maxsize); // create the arrayint count; For (INT I = 19; I> = 0; I --) {// The array is initialized as an array in reverse order. insert (I);} arr. insert (19); arr. insert (9); arr. insert (0); arr. display (); Count = arr. insertionsort1 (); arr. display (); system. out. println ("Reverse Order array compare total number of copies:" + count); // meet O (N ^ 2) Arr = new arrayins (maxsize ); // create the arrayfor (INT I = 0; I <= 19; I ++) {// initialize it as an ordered array arr. insert (I);} arr. insert (19); arr. insert (9); arr. insert (0); arr. display (); Count = arr. insertionsort1 (); arr. display (); system. out. println ("sequential array compare total number of copies:" + count); // meet O (N) // ================================================ // programming job 3.6 p79 (98) arr = new arrayins (maxsize); // create the arrayarr. insert (2); arr. insert (3); arr. insert (4); arr. insert (3); arr. insert (3); arr. insert (1); arr. insert (2); arr. insert (1); arr. insert (1); arr. insert (1); system. out. println ("after repeated values are inserted:"); arr. display (); arr. insertionsort2 (); system. out. println ("after the duplicate value is deleted:"); arr. display (); // ================================================} // end main ()} // end class insertsortapp