A place for everything and everything in its place.
*4"#&--"."3:#&&50/THE BOOK OF HOUSEHOLD MANAGEMENT (1861)
4VQQPTF ZPV IBWF BO BSSBZ PG WBMVFT :PV NJHIU XBOU UIF BSSBZ WBMVFT UP CF PSEFSFE JO TPNF XBZ 'PS FYBNQMF ZPV NJHIU XBOU UP PSEFS BO BSSBZ PG OVNCFSTGSPNMPXFTUUPIJHIFTUPSGSPNIJHIFTUUPMPXFTUPSZPVNJHIUXBOU to arrange an array of strings into alphabetical order. Arranging a collection of items into a particular order is called sorting.5ZQJDBMMZXFTPSUBSSBZTJOUP ascending or descending order.
*OUIJTTFDUJPOXFXJMMEJTDVTTBOEJNQMFNFOUBTJNQMFTPSUJOHBMHPSJUIN 8FXJMMQSFTFOUUIJTBMHPSJUINBTBXBZUPTPSUBOBSSBZPGJOUFHFST)PXFWFS XJUIPOMZNJOPSDIBOHFTJUDBOCFBEBQUFEUPTPSUBSSBZTPGWBMVFTPGBOZUZQF UIBUDBOCFPSEFSFE'PSFYBNQMFXFDPVMETPSUBOBSSBZPGFNQMPZFFSFDPSET according to identification numbers.
We also will consider searching a given array for a particular entry. We can search an array whose entries are sorted or one whose entries are completely VOPSHBOJ[FE #PUI TPSUJOH BOE TFBSDIJOH BSF RVJUF JNQPSUBOU UBTLT BOE FGGJDJFOU BMHPSJUINT BSF JNQPSUBOU 8F XJMM IPXFWFS KVTU JOUSPEVDF ZPV UP these topics.
Selection Sort
*NBHJOFBOBSSBZPGJOUFHFSTUIBUXFXBOUUPTPSUJOUPBTDFOEJOHPSEFS5IBUJT XFXJMMSFBSSBOHFUIFWBMVFTJOUIFJOEFYFEWBSJBCMFTPGUIFBSSBZTPUIBU
a[0] ≤ a[1] ≤ a[2] ≤ ... ≤ a[a.length - 1]
8FXJMMEJTDVTTPOFPGUIFFBTJFTUPGUIFTPSUJOHBMHPSJUINTUPVOEFSTUBOEUIF selection sort. This algorithm follows from the specification of what we want UIFBMHPSJUINUPEP5IBUJTXFXBOUUIFBMHPSJUINUPSFBSSBOHFUIFWBMVFTPG the array a so that a[0]JTUIFTNBMMFTUa[1]JTUIFOFYUTNBMMFTUBOETPGPSUI That desire leads to the following pseudocode:
for (index = 0; index <a.length; index++)
Place the (index + 1)th smallest element in a[index]
3FQFBUUIFQSFWJPVTRVFTUJPOCVUUIJTUJNFBTTVNFUIBUZPVEPOPULOPX whether the array a is full. If the array aJTGVMMZPVSDPEFTIPVMEEJTQMBZ an appropriate message to the screen.
22. Write an accessor method getEntryArray for the class OneWayNoRepeatsList that returns a copy of the array entry4JODFentry JTBOBSSBZPGTUSJOHTZPVOFFEOPUDPQZUIFTUSJOHTUIFNTFMWFT
Sorting arranges array elements into a particular order, such as ascending or descending
526 CHAPTER 7 / Arrays
We want this algorithm to use only the one array a5IVTUIFPOMZXBZ we can move an array element without losing any of the other elements is to make it swap places with another element of the array. Any sorting algorithm UIBUTXBQTPSJOUFSDIBOHFTWBMVFTJTDBMMFEBOinterchange sorting algorithm.
5IVTPVSTFMFDUJPOTPSUBMHPSJUINJTBOJOUFSDIBOHFTPSUJOHBMHPSJUIN
-FUTTUBSUXJUIBOFYBNQMFUPTFFIPXUIFBSSBZFMFNFOUTBSFJOUFSDIBOHFE 'JHVSF TIPXT IPX BO BSSBZ JT TPSUFE CZ JOUFSDIBOHJOH WBMVFT #FHJOOJOH Interchange sorts
swap values in an array
FIGURE 7.5 Selection Sort
7 a[0]
6 a[1]
11 a[2]
17 a[3]
3 a[4]
15
Unsorted array
Sorted array a[5]
5 a[6]
19 a[7]
30 a[8]
14
7 6 11 17 3 15 5 19 30 14
3 6 11 17 7 15 5 19 30 14
3 6 11 17 7 15 5 19 30 14
3 5 11 17 7 15 6 19 30 14
3 5 6 7 11 14 15 17 19 30
a[9]
XJUIBOBSSBZPGVOTPSUFEWBMVFTXFMPDBUFUIFTNBMMFTUWBMVFJOUIFBSSBZ*O PVSFYBNQMFUIJTWBMVFJTUIFJOa[4]4JODFXFXBOUUIJTTNBMMFTUWBMVFUP CFGJSTUJOUIFBSSBZXFJOUFSDIBOHFUIFWBMVFJOa[4] with the value in a[0].
"GUFSUIBUJOUFSDIBOHFUIFTNBMMFTUWBMVFJTJOa[0] where it belongs.
5IFOFYUTNBMMFTUWBMVFJOUIFBSSBZJTUIFJOa[6]. It needs to be second in UIFBSSBZTPXFJOUFSDIBOHFUIFWBMVFJOa[6] with the value in a[1]. After that TXBQUIFWBMVFTJOa[0] and a[1]BSFUIFTNBMMFTUBOEOFYUTNBMMFTUWBMVFTXIJDI is what they should be in the final sorted array. The algorithm then interchanges UIFOFYUTNBMMFTUFMFNFOUXJUIa[2] and so forth until the entire array is sorted.
'JOEJOHUIFTNBMMFTUWBMVFJOBOBSSBZJTBOBMPHPVTUPGJOEJOHUIFMBSHFTU WBMVFBOEXFEJEUIBUJOUIFNFUIPEcomputeStatsJO-JTUJOH#VUIPXEP XFGJOEUIFTFDPOETNBMMFTUWBMVFUIFUIJSETNBMMFTUBOETPPO "GUFSGJOEJOH the smallest value among a[0]a[1]. . .a[n] and placing it into a[0]UIF second smallest value in the array a is the smallest value among a[1]. . . a[n]. After placing it into a[2] UIF UIJSE TNBMMFTU WBMVF JOa is the smallest value among a[2]. . . a[n]BOETPPO
The following pseudocode describes the selection sort algorithm:
Algorithm for a selection sort of an array for (index = 0; index <a.length − 1; index++) { // Place the correct value in a[index]:
indexOfNextSmallest = the index of the smallest value among a[index], a[index+1],...,
a[a.length - 1]
Interchange the values of a[index] and
a[indexOfNextSmallest].
//Assertion: a[0] <= a[1] <= ... <= a[index] and these //are the smallest of the original array elements.
//The remaining positions contain the rest of the //original array elements.
}
Notice that we effectively have two regions of the array: One region is TPSUFEBOEUIFPUIFSJTOPU5IFBTTFSUJPOJOPVSBMHPSJUINJNQMJFTUIBUUIF sorted region encompasses the elements a[0] through a[index]. Notice that this assertion is true after each iteration of the loop. We repeatedly find the smallest value in the unsorted region and move it to the end of the sorted SFHJPOCZTXBQQJOHFMFNFOUT5IVTUIFTPSUFESFHJPOHSPXTCZPOFFMFNFOUBU FBDISFQFUJUJPOPGUIFMPPQXIJMFUIFVOTPSUFESFHJPOTISJOLTCZPOFFMFNFOU
*O'JHVSFUIFTPSUFESFHJPOJTTIBEFECMVF
Note that the for loop ends after correctly filling the element a[a.length − 2]FWFOUIPVHIUIFJOEFYPGUIFMBTUBSSBZFMFNFOUJTa.length − 1.
"GUFSUIFBMHPSJUINHFUTBMMCVUPOFFMFNFOUTPSUFEUIFDPSSFDUWBMVFGPSUIF last element a[a.length − 1] is already in a[a.length − 1].
-JTUJOHDPOUBJOTBDMBTTEFGJOJOHBTUBUJDNFUIPEOBNFEselectionSort that implements this selection sort algorithm. The method uses two private helping methods named getIndexOfSmallest and interchange. Once you
Pseudocode for a selection sort
528 CHAPTER 7 / Arrays
LISTING 7.10 Implementation of the Selection Sort (part 1 of 2) /**
Class for sorting an array of base type int from smallest to largest.
*/
public class ArraySorter {
/**
Precondition: Every element in anArray has a value.
Action: Sorts the array into ascending order.
*/
public static void selectionSort(int[] anArray) {
for (int index = 0; index < anArray.length − 1; index++) { // Place the correct value in anArray[index]
int indexOfNextSmallest = getIndexOfSmallest(index, anArray);
interchange(index, indexOfNextSmallest, anArray);
//Assertion:anArray[0] <= anArray[1] <=...<= anArray[index]
//and these are the smallest of the original array elements.
//The remaining positions contain the rest of the original //array elements.
} }
/**
Returns the index of the smallest value in the portion of the array that begins at the element whose index is startIndex and ends at the last element.
*/
private static int getIndexOfSmallest(int startIndex, int[] a) {
int min = a[startIndex];
int indexOfMin = startIndex;
for (int index = startIndex + 1; index < a.length; index++) {
if (a[index] < min) {
min = a[index];
indexOfMin = index;
//min is smallest of a[startIndex] through a[index]
} }
return indexOfMin;
}
(continued) VOEFSTUBOE UIFTF QSJWBUF NFUIPET ZPV XJMM TFF UIBU UIF EFGJOJUJPO PG UIF method selectionSort is a direct translation of our pseudocode into Java code.
4PMFUTEJTDVTTUIFTFUXPQSJWBUFNFUIPET
LISTING 7.10 Implementation of the Selection Sort (part 2 of 2) /**
Precondition: i and j are valid indices for the array a.
Postcondition: Values of a[i] and a[j] have been interchanged.
*/
private static void interchange(int i, int j, int[] a) {
int temp = a[i];
a[i] = a[j];
a[j] = temp; //original value of a[i]
} }
The method getIndexOfSmallest searches the array elements a[startIndex], a[startIndex + 1], . . . , a[a.length - 1]
BOE SFUVSOT UIF JOEFY PG UIF TNBMMFTU POF *U EPFT UIJT VTJOH UIF UXP MPDBM variables min and indexOfMin"UBOZQPJOUJOJUTTFBSDIminJTFRVBMUPUIF TNBMMFTUBSSBZWBMVFGPVOETPGBSBOEindexOfMinJTUIFJOEFYPGUIBUWBMVF 5IVTa[indexOfMin] has the value min*OJUJBMMZmin is set to a[startIndex]
which is the first value considered for min BOE indexOfMin is set to startIndex. Then each array element is considered in turn to see whether it is BOFXNJOJNVN*GJUJTUIFWBMVFTPGmin and indexOfMin are updated. After DIFDLJOHBMMPGUIFDBOEJEBUFBSSBZFMFNFOUTUIFNFUIPESFUVSOTUIFWBMVFPG indexOfMin.
The method named interchange interchanges the values of a[i] and a[j]. 5IFSFJTPOFTVCUMFQPJOUBCPVUUIJTNFUIPE*GZPVFYFDVUFUIFDPEF
a[i] = a[j];
you will lose the value originally held in a[i] 4P CFGPSF UIJT TUBUFNFOU JT FYFDVUFEXFNVTUTBWFUIFWBMVFPGa[i] in the local variable temp.
-JTUJOHDPOUBJOTBEFNPOTUSBUJPOQSPHSBNUIBUTIPXTUIFTFMFDUJPO sort method in action.
Other Sorting Algorithms
Although the selection sort algorithm will suffice as an introduction to the HFOFSBMUPQJDPGTPSUJOHJUJTOPUUIFNPTUFGGJDJFOUTPSUJOHBMHPSJUIN*OGBDUJU is significantly less efficient than a number of well-known sorting algorithms.
5IFTFMFDUJPOTPSUJTIPXFWFSNVDITJNQMFSUIBOUIFTFPUIFSBMHPSJUINT"
TJNQMFSBMHPSJUINJTMFTTMJLFMZUPIBWFFSSPSTDSFFQJOXIFOZPVDPEFJU4P JGZPVOFFEUPDPEFBTPSUJOHBMHPSJUINJOBIVSSZJUJTTBGFSUPVTFFJUIFSB selection sort or some other simple algorithm.
Find the next smallest entry in the array
Place the next entry in its correct position by swapping
Selection sort is simple, but not the fastest way to sort
530 CHAPTER 7 / Arrays
LISTING 7.11 Demonstration of the Method selectionSort public class SelectionSortDemo
{
public static void main(String[] args) {
int[] b = {7, 5, 11, 2, 16, 4, 18, 14, 12, 30};
display(b, "before");
ArraySorter.selectionSort(b);
display(b, "after");
}
public static void display(int[] array, String when) {
System.out.println("Array values " + when + " sorting:");
for (int i = 0; i < array.length; i++) System.out.print(array[i] + " ");
System.out.println( );
} }
Screen Output
Array values before sorting:
7 5 11 2 16 4 18 14 12 30 Array values after sorting:
2 4 5 7 11 12 14 16 18 30
0OUIFPUIFSIBOEJGFGGJDJFODZJTBNBKPSJTTVFZPVNBZXJTIUPVTFB NPSFDPNQMJDBUFEBOENPSFFGGJDJFOUBMHPSJUIN#VUCFBXBSFUIBUUIFNPSF DPNQMJDBUFEBMHPSJUINXJMMUBLFMPOHFSUPDPEFUFTUBOEEFCVH&GGJDJFODZDBO CFBTVCUMFUPQJD3FNFNCFSHFUUJOHUIFXSPOHSFTVMUJTBMXBZTJOFGGJDJFOUOP NBUUFSIPXRVJDLMZZPVSQSPHSBNDBODPNFVQXJUIUIFSFTVMU
'PSUVOBUFMZUIF+BWB$MBTT-JCSBSZQSPWJEFTGPSFGGJDJFOUTPSUJOH5IFDMBTT ArraysJOUIFQBDLBHFjava.utilEFGJOFTUIFTUBUJDNFUIPEsort. If anArray JTBOBSSBZPGFJUIFSQSJNJUJWFWBMVFTPSPCKFDUTUIFTUBUFNFOU
Arrays.sort(anArray);
sorts the elements in the entire array into ascending order. To sort only the QPSUJPO PG UIF BSSBZ CFHJOOJOH XJUI UIF JOEFYfirst and ending with the JOEFYlastZPVXPVMEXSJUF
Arrays.sort(anArray, first, last);
The class ArraysEFGJOFTTFWFSBMWFSTJPOTPGUIFNFUIPEUIBUJTUIFOBNFsort is overloaded—to accommodate arrays of class types as well as all the primitive types.
1SPHSBNNJOH 1SPKFDUT BOE BU UIF FOE PG UIJT DIBQUFS EFTDSJCF UXP other sorting algorithms. A more efficient sorting algorithm—one similar to the algorithm that Arrays.sort uses—is described in Chapter 11 when we talk about recursion.
S E L F - T E S T Q U E S T I O N S
5SBDFUIFTUFQTUIBUBTFMFDUJPOTPSUUBLFTBTJUTPSUTUIFGPMMPXJOHBSSBZJOUP BTDFOEJOHPSEFS
8SJUF UIF JOWPDBUJPO PG UIF NFUIPEselectionSort to sort an array myArray of integers into ascending order.
)PXXPVMEZPVOFFEUPDIBOHFUIFNFUIPEselectionSort so that it can sort an array of values of type double instead of type int
)PX XPVME ZPV OFFE UP DIBOHF UIF NFUIPEselectionSort so that it can sort an array of values of type int JOUP EFDSFBTJOH PSEFS JOTUFBE PG JODSFBTJOHPSEFS
$POTJEFS BO BSSBZb of int WBMVFT JO XIJDI B WBMVF PDDVST UXJDF 'PS FYBNQMF TVQQPTF PDDVST JO CPUIb[0] and b[5]. If you sort the array using the method selectionSort XJMM UIF TPSUFE BSSBZ DPOUBJO POF PS UXPDPQJFTPGUIFSFQFBUFEWBMVF
Searching an Array
The method isOnList of the class OneWayNoRepeatsList JO -JTUJOH searches the array entry to see whether it contains the value represented by the parameter item 5IJT JT BO FYBNQMF PG Bsequential search of an array.
5IF TFRVFOUJBM TFBSDI BMHPSJUIN JT WFSZ TJNQMF BOE TUSBJHIUGPSXBSE *U MPPLT at the array elements from first to last to see whether the sought-after item is FRVBMUPBOZPGUIFBSSBZFMFNFOUT5IFTFBSDIFOETXIFOFJUIFSUIFEFTJSFE item is found in the array or the end of the array is reached without finding UIFJUFN*OUIFMBUUFSDBTFPGDPVSTFUIFTFBSDIJTVOTVDDFTTGVM*GUIFBSSBZJT QBSUJBMMZGJMMFEUIFTFBSDIDPOTJEFSTPOMZUIFQPSUJPOPGUIFBSSBZUIBUDPOUBJOT meaningful values.
"TFRVFOUJBMTFBSDIDBOTFBSDIBOVOTPSUFEBSSBZXIJDIJTBOBEWBOUBHF PGUIJTTJNQMFBMHPSJUIN*GIPXFWFSUIFBSSBZJTTPSUFEXFDBOJNQSPWFUIF TFRVFOUJBMTFBSDIJOTJUVBUJPOTJOXIJDIUIFEFTJSFEJUFNEPFTOPUFYJTUXJUIJO UIF BSSBZ &YFSDJTF BTLT ZPV UP XSJUF UIJT JNQSPWFE TFRVFOUJBM TFBSDI "O FWFOGBTUFSBMHPSJUINUIFCJOBSZTFBSDIJTQPTTJCMFGPSTPSUFEBSSBZT8FXJMM study this algorithm in Chapter 11.
A sequential search looks for an array element from beginning to end
532 CHAPTER 7 / Arrays