Download presentation
Presentation is loading. Please wait.
Published byYohanes Hadian Kartawijaya Modified over 6 years ago
1
Chapter 12 – JavaScript/Jscript: Arrays
Outline 12.1 Introduction 12.2 Arrays 12.3 Declaring and Allocating Arrays 12.4 Examples Using Arrays 12.5 References and Reference Parameters 12.6 Passing Arrays to Functions 12.7 Sorting Arrays 12.8 Searching Arrays: Linear Search and Binary Search 12.9 Multiple-Subscripted Arrays
2
JavaScript arrays are “dynamic” entities
12.1 Introduction Arrays Data structures consisting of related data items (collections of data items) JavaScript arrays are “dynamic” entities Can change size after being created
3
Array - group of memory locations that
12.2 Arrays Array - group of memory locations that All have the same name Are normally of the same type (though not required) To refer to particular element in array, specify The name of the array The position number of the particular element in the array Example (to identify the 5th element in array c): c[4] Position number in brackets called a subscript (or index) If program uses an expression as a subscript, expression is evaluated first to determine the subscript
4
First element in every array is the zeroth (0th) element
12.2 Arrays (II) First element in every array is the zeroth (0th) element Therefore, element n will have a subscript value of (n-1) Length of an Array determined by the expression arrayName.length Brackets Used to enclose the subscript of an array Have same precedence in JavaScript operations as parentheses
5
12.2 Arrays (III) A 12-element Array 78 -45 6 72 1543 -89 62 -3 1 6453
72 1543 -89 62 -3 1 6453 c[0] c[1] c[2] c[3] c[4] c[5] c[6] c[8] c[10] c[9] c[7] c[11] 1st Element 2nd Element 3rd Element 4th Element 5th Element 6th Element 7th Element 9th Element 11th Element 10th Element 8th Element 12th Element Position numbers of elements in array c Name of array - c Element Values
6
12.3 Declaring and Allocating Arrays
An array in JavaScript is an Array object Operator new creates an object as the program executes Obtains enough memory to store an object of the type specified Process of creating objects also known as Creating an instance or Instantiating an object new Dynamic memory allocation operator
7
12.3 Declaring and Allocating Arrays (II)
To allocate 12 elements for integer array c var c = new Array( 12 ); This can also be performed in 2 steps: var c; c = new Array( 12 ); When arrays allocated, elements not initialized Reserving memory Use a single declaration: var b = new Array( 100 ), x = new Array( 27 ); Reserves 100 elements for array b, 27 elements for array x
8
Arrays can be initialized with existing elements
12.4 Examples Using Arrays Arrays can be initialized with existing elements var n1 = new Array( 5 ); Initializes array n1 with 5 elements Arrays can also be initialized with no elements Grow dynamically to accommodate new elements var n2 = new Array(); Initializes empty array n2 Element values can be printed using the regular writeln method document.writeln( “The value is “ + n2[2] );
9
1.1 Define initializeArrays function
1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> 2 <HTML> 3 <!-- Fig. 12.3: InitArray.html --> 4 5 <HEAD> 6 <TITLE>Initializing an Array</TITLE> 7 8 <SCRIPT LANGUAGE = "JavaScript"> 9 // this function is called when the <BODY> element's 10 // ONLOAD event occurs 11 function initializeArrays() 12 { var n1 = new Array( 5 ); // allocate 5-element Array var n2 = new Array(); // allocate empty Array 15 // assign values to each element of Array n1 for ( var i = 0; i < n1.length; ++i ) n1[ i ] = i; 19 // create and initialize five-elements in Array n2 for ( i = 0; i < 5; ++i ) n2[ i ] = i; 23 outputArray( "Array n1 contains", n1 ); outputArray( "Array n2 contains", n2 ); 26 } 27 1.1 Define initializeArrays function 1.2 Initialize variables, and create new arrays 1.3 Assign values to each element in Array n1 1.4 Create and initialize five elements in Array n2 1.5 Use function outputArray to display contents of Arrays n1 and n2
10
2.1 Define outputArray function
31 { document.writeln( "<H2>" + header + "</H2>" ); document.writeln( "<TABLE BORDER = '1' WIDTH = '100%'>" ); document.writeln( "<TR><TD WIDTH = '100'><B>Subscript</B>" "<TD><B>Value</B></TR>" ); 36 for ( var i = 0; i < theArray.length; i++ ) document.writeln( "<TR><TD>" + i + "<TD>" + theArray[ i ] + "</TR>" ); 40 document.writeln( "</TABLE>" ); 42 } 43 </SCRIPT> 44 45 </HEAD><BODY ONLOAD = "initializeArrays()"></BODY> 46 </HTML> 28 // output "header" followed by a two-column table 29 // containing subscripts and elements of "theArray" 30 function outputArray( header, theArray ) 2.1 Define outputArray function 2.2 Open HTML TABLE 2.3 Print contents of the array inside the table 2.4 Close the TABLE 3.1 Set BODY element to execute function initializeArrays when the page loads
11
Script Output
12
12.4 Examples Using Arrays (II)
The elements of an Array can be allocated and initialized in the array declaration This can be done in two ways To initialize array n with five known elements: var n = [ 10, 20, 30, 40, 50 ]; Uses a comma-separated initializer list enclosed in square brackets var n = new Array( 10, 20, 30, 40, 50 )
13
12.4 Examples Using Arrays (III)
To reserve a space in an Array for an unspecified value Use a comma as a place holder in the initializer list var n = [ 10, 20, , 40, 50 ]; Creates five element array with no value specified for n[2] n[2] will appear undefined until a value for it is initialized
14
1.3 Use outputArray function to print the array’s contents
1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> 2 <HTML> 3 <!-- Fig. 12.4: InitArray.html --> 4 5 <HEAD> 6 <TITLE>Initializing an Array with a Declaration</TITLE> 7 8 <SCRIPT LANGUAGE = "JavaScript"> 9 function start() 10 { // Initializer list specifies number of elements and // value for each element. var colors = new Array( "cyan", "magenta", "yellow", "black" ); var integers1 = [ 2, 4, 6, 8 ]; var integers2 = [ 2, , , 8 ]; 17 outputArray( "Array colors contains", colors ); outputArray( "Array integers1 contains", integers1 ); outputArray( "Array integers2 contains", integers2 ); 21 } 22 1.1 Define start function 1.2 Initialize and set element values for arrays colors, integers1 and integers2 1.3 Use outputArray function to print the array’s contents
15
2.1 Define outputArray function
for ( var i = 0; i < theArray.length; i++ ) document.writeln( "<TR><TD>" + i + "<TD>" + theArray[ i ] + "</TR>" ); 35 document.writeln( "</TABLE>" ); 37 } 38 </SCRIPT> 39 40 </HEAD><BODY ONLOAD = "start()"></BODY> 41 </HTML> 23 // output "header" followed by a two-column table 24 // containing subscripts and elements of "theArray" 25 function outputArray( header, theArray ) 26 { document.writeln( "<H2>" + header + "</H2>" ); document.writeln( "<TABLE BORDER = '1' WIDTH = '100%'>" ); document.writeln( "<TR><TD WIDTH = '100'><B>Subscript</B>" "<TD><B>Value</B></TR>" ); 31 2.1 Define outputArray function 2.2 open HTML TABLE 2.3 Print the contents of array inside the table 2.4 Close TABLE 3.1 Set BODY element to execute function initializeArrays when the page loads
16
Script Output
17
12.4 Examples Using Arrays (IV)
for/in repetition structure Enables a script to perform a task for each element in an array Also known as iterating over the array elements Format: for ( var element in theArray ) total2 += theArray[ element ]; Adds the value every element in array theArray to total2 Structure ends after an iteration has been done for every element in theArray
18
1.2 Initialize variables and arrays theArray
1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> 2 <HTML> 3 <!-- Fig. 12.5: SumArray.html --> 4 5 <HEAD> 6 <TITLE>Sum the Elements of an Array</TITLE> 7 8 <SCRIPT LANGUAGE = "JavaScript"> 9 function start() 10 { var theArray = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]; var total1 = 0, total2 = 0; 13 for ( var i = 0; i < theArray.length; i++ ) total1 += theArray[ i ]; 16 document.writeln( "Total using subscripts: " + total1 ); 18 for ( var element in theArray ) total2 += theArray[ element ]; 21 document.writeln( "<BR>Total using for/in: " + total2 ); 23 } 24 </SCRIPT> 25 26 </HEAD><BODY ONLOAD = "start()"></BODY> 27 </HTML> 1.1 define start function 1.2 Initialize variables and arrays theArray 1.3 Use for structure to calculate sum of all elements in theArray 1.4 Print results 1.5 Use for/in structure to calculate sum of all elements in theArray 1.6 Print results 2.1 Set BODY element to call start when page loads
19
Script Output
20
1.2 Initialize variables and arrays responses and frequency
1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> 2 <HTML> 3 <!-- Fig. 12.6: StudentPoll.html --> 4 5 <HEAD> 6 <TITLE>Student Poll Program</TITLE> 7 8 <SCRIPT LANGUAGE = "JavaScript"> 9 function start() 10 { var responses = [ 1, 2, 6, 4, 8, 5, 9, 7, 8, 10, , 6, 3, 8, 6, 10, 3, 8, 2, 7, , 5, 7, 6, 8, 6, 7, 5, 6, 6, , 6, 7, 5, 6, 4, 8, 6, 8, 10 ]; var frequency = [ , 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]; 16 for ( var answer in responses ) frequency[ responses[ answer ] ]; 19 document.writeln( "<TABLE BORDER = '1' WIDTH = '100%'>" ); document.writeln( "<TR><TD WIDTH = '100'><B>Rating</B>" + "<TD><B>Frequency</B></TR>" ); 23 for ( var rating = 1; rating < frequency.length; ++rating ) document.writeln( "<TR><TD>" + rating + "<TD>" + frequency[ rating ] + "</TR>" ); 28 document.writeln( "</TABLE>" ); 30 } 31 </SCRIPT> 32 </HEAD><BODY ONLOAD = "start()"></BODY> 33 </HTML> 1.1 Define start function 1.2 Initialize variables and arrays responses and frequency 1.3 Use for/in structure to classify responses 2.1 Open HTML TABLE 2.2 Use for structure to print results 2.3 Close TABLE 3.1 Set BODY element to call start when page loads
21
Script Output
22
12.4 Examples Using Arrays (V)
When value assigned to an Array element that is outside current bounds JavaScript automatically allocates more memory New elements added automatically without values assigned to them are are undefined by JavaScript Tips In loops with arrays, check that range of loop is inside range of array Programs should validate correctness of all input values
23
1.2 Initialize array theArray
1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> 2 <HTML> 3 <!-- Fig. 12.7: Histogram.html --> 4 5 <HEAD> 6 <TITLE>Histogram Printing Program</TITLE> 7 8 <SCRIPT LANGUAGE = "JavaScript"> 9 function start() 10 { var theArray = [ 19, 3, 15, 7, 11, 9, 13, 5, 17, 1 ]; 12 document.writeln( "<TABLE BORDER = '1' WIDTH = '100%'>" ); document.writeln( "<TR><TD WIDTH = '100'><B>Element</B>" + "<TD WIDTH = '100'><B>Value</B>" + "<TD><B>Histogram</B></TR>" ); 17 for ( var i in theArray ) { document.writeln( "<TR><TD>" + i + "<TD>" + theArray[ i ] + "<TD>" ); 21 // print a bar for ( var j = 1; j <= theArray[ i ]; ++j ) document.writeln( "*" ); 25 document.writeln( "</TR>" ); } 28 document.writeln( "</TABLE>" ); 30 } 31 </SCRIPT> 32 33 </HEAD><BODY ONLOAD = "start()"></BODY> 34 </HTML> 1.1 Define start function 1.2 Initialize array theArray 2.1 Print TABLE header 3.1 Use for/in structure to print element info 3.2 Use for structure to print histogram 4.1 Close TABLE 5.1 Set BODY element to call start when loaded
24
Script Output
25
1.1 Initialize variables, array frequency
1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> 2 <HTML> 3 <!-- Fig. 12.8: RollDie.html --> 4 5 <HEAD> 6 <TITLE>Roll a Six-Sided Die 6000 Times</TITLE> 7 8 <SCRIPT LANGUAGE = "JavaScript"> 9 var face, frequency = [ , 0, 0, 0, 0, 0, 0 ]; 10 11 // summarize results 12 for ( var roll = 1; roll <= 6000; ++roll ) { face = Math.floor( 1 + Math.random() * 6 ); frequency[ face ]; 15 } 16 17 document.writeln( "<TABLE BORDER = '1' WIDTH = '100%'>" ); 18 document.writeln( "<TR><TD WIDTH = '100'><B>Face</B>" + "<TD><B>Frequency</B></TR>" ); 20 21 for ( face = 1; face < frequency.length; ++face ) document.writeln( "<TR><TD>" + face + "<TD>" + frequency[ face ] + "</TR>" ); 24 25 document.writeln( "</TABLE>" ); 26 </SCRIPT> 27 28 </HEAD> 29 <BODY> 30 <P>Click Refresh (or Reload) to run the script again</P> 31 </BODY> 32 </HTML> 1.1 Initialize variables, array frequency 2.1 Use for structure to roll dice 6000 times and input statistics into array frequency 3.1 Open HTML TABLE 4.1 Use for structure to input array data into table 4.2 Close TABLE
26
Script Output
27
12.5 References and Reference Parameters
Two ways to pass arguments to functions Call-by-value / pass-by-value When used to pass argument, copy of value is made and passed to called function Takes up more space, uses more power, but more secure and eliminates many potential problems Used in JavaScript for numbers or boolean values Call-by-reference / pass-by-reference When used to pass argument, location in memory / address of argument is passed to called function Takes up less space, uses less power, but less secure and allows many potential problems to occur Used in JavaScript for objects, including Arrays
28
12.6 Passing Arrays to Functions
To pass an array to a function Specify the name of the array without brackets as a parameter You do not need to separately pass the size of the array Individual numeric and boolean array elements are Passed exactly as simple numeric and boolean variables: call-by-value Simple single pieces of data are called scalars or scalar qualities Are passed using subscripted name of the array element
29
12.6 Passing Arrays to Functions (II)
For function to receive Array through a function call Must specify parameter that will be used to refer to the array in the body of the function JavaScript does not provide a special syntax for this purpose arrayName.join( x ); Creates string containing all elements in arrayName Takes argument – string containing separator – used to separate elements of the array in the string when returned If argument left empty – empty string used as separator
30
1.2 Initialize array a, set element values
1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> 2 <HTML> 3 <!-- Fig. 12.9: PassArray.html --> 4 5 <HEAD> 6 <TITLE>Passing Arrays and Individual Array Elements to Functions</TITLE> 8 9 <SCRIPT LANGUAGE = "JavaScript"> 10 function start() 11 { var a = [ 1, 2, 3, 4, 5 ]; 13 document.writeln( "<H2>Effects of passing entire " + "array call-by-reference</H2>" ); outputArray( "The values of the original array are: ", a ); 18 modifyArray( a ); // array a passed call-by-reference 20 outputArray( "The values of the modified array are: ", a ); 23 document.writeln( "<H2>Effects of passing array " + "element call-by-value</H2>" + "a[3] before modifyElement: " + a[ 3 ] ); 27 modifyElement( a[ 3 ] ); 29 document.writeln( "<BR>a[3] after modifyElement: " + a[ 3 ] ); 32 } 1.1 Define start function 1.2 Initialize array a, set element values 1.3 Print results 1.4 Call outputArray function 1.5 Call modifyArray function 1.6 Print results 1.7 Run modifyElement function
31
2.1 Define outputArray function
33 34 // outputs "header" followed by the contents of "theArray" 35 function outputArray( header, theArray ) 36 { document.writeln( header + theArray.join( " " ) + "<BR>" ); 39 } 40 41 // function that modifies the elements of an array 42 function modifyArray( theArray ) 43 { for ( var j in theArray ) theArray[ j ] *= 2; 46 } 47 48 // function that attempts to modify the value passed 49 function modifyElement( e ) 50 { e *= 2; document.writeln( "<BR>value in modifyElement: " + e ); 53 } 54 </SCRIPT> 55 56 </HEAD><BODY ONLOAD = "start()"></BODY> 57 </HTML> 2.1 Define outputArray function 2.2 Print Array string 3.1 Define modifyArray function 3.2 Execute for structure actions 4.1 Define modifyElement function 4.2 Print results 5.1 Set BODY element to call start when page is loaded
32
Script Output
33
Sorting data is one of most important computing scripts
12.7 Sorting Arrays Sorting data is one of most important computing scripts Virtually every organization must sort data in some amount Bubble sort or sinking sort technique Smaller values gradually rise or “bubble” their way to top Makes several passes through the array On each pass successive pairs of elements compared If pair in increasing order, left as is If pair in decreasing order, values are swapped Easy to program but runs slowly Not good for sorting large arrays
34
2.1 Define outputArray function
1 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> 2 <HTML> 3 <!-- Fig : BubbleSort.html --> 4 5 <HEAD> 6 <TITLE>Sorting an Array with Bubble Sort</TITLE> 7 8 <SCRIPT LANGUAGE = "JavaScript"> 9 function start() 10 { var a = [ 10, 1, 9, 2, 8, 3, 7, 4, 6, 5 ]; 12 document.writeln( "<H1>Sorting an Array</H1>" ); outputArray( "Data items in original order: ", a ); bubbleSort( a ); // sort the array outputArray( "Data items in ascending order: ", a ); 17 } 18 19 // outputs "header" followed by the contents of "theArray" 20 function outputArray( header, theArray ) 21 { document.writeln( "<P>" + header + theArray.join( " " ) + "</P>" ); 24 } 25 26 // sort the elements of an array with bubble sort 27 function bubbleSort( theArray ) 28 { // control number of passes of theArray for ( var pass = 1; pass < theArray.length; ++pass ) 1.1 Define start function 1.2 Initialize array a 1.3 Call outputArray 1.4 Call bubbleSort 1.5 Call outputArray 2.1 Define outputArray function 2.2 Print array data 3.1 Define bubbleSort function 3.2 Use for to control theArray passes
35
3.3 Use for to control number comparisons per pass
31 // one pass - control's number of comparison per pass for ( var i = 0; i < theArray.length - 1; ++i ) 34 // perform one comparison if ( theArray[ i ] > theArray[ i + 1 ] ) swap( theArray, i, i + 1 ); // swap elements 38 } 39 40 // swap two elements of an array 41 function swap( theArray, first, second ) 42 { var hold; // temporary holding area for swap 44 hold = theArray[ first ]; theArray[ first ] = theArray[ second ]; theArray[ second ] = hold; 48 } 49 </SCRIPT> 50 51 </HEAD><BODY ONLOAD = "start()"></BODY> 52 </HTML> 3.3 Use for to control number comparisons per pass 3.4 Use if to perform one comparison 3.5 Call swap to swap values where needed 4.1 Define swap function 4.2 Set swap structure variables and actions 5.1 Set BODY to call start when page loaded
36
Script Output
37
JavaScript has built in method sort for sorting arrays
12.7 Sorting Arrays (II) JavaScript has built in method sort for sorting arrays By default uses string comparisons to determine sorting order of Array elements Strings compared by ASCII values of their characters Takes as optional argument name of function (comparator function) – compares two arguments and returns following Negative value if first value < second value Zero if arguments are equal Positive value if first value > second value Functions can be considered data and be assigned to variables and passed to functions
38
2.1 Define outputArray function
1 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> 2 <HTML> 3 <!-- Fig : sort.html --> 4 5 <HEAD> 6 <TITLE>Sorting an Array with Array Method sort</TITLE> 7 8 <SCRIPT LANGUAGE = "JavaScript"> 9 function start() 10 { var a = [ 10, 1, 9, 2, 8, 3, 7, 4, 6, 5 ]; 12 document.writeln( "<H1>Sorting an Array</H1>" ); outputArray( "Data items in original order: ", a ); a.sort( compareIntegers ); // sort the array outputArray( "Data items in ascending order: ", a ); 17 } 18 19 // outputs "header" followed by the contents of "theArray" 20 function outputArray( header, theArray ) 21 { document.writeln( "<P>" + header + theArray.join( " " ) + "</P>" ); 24 } 25 26 // comparison function for use with sort 27 function compareIntegers( value1, value2 ) 28 { return parseInt( value1 ) - parseInt( value2 ); 30 } 31 </SCRIPT> 32 33 </HEAD><BODY ONLOAD = "start()"></BODY> 34 </HTML> 1.1 Define start function 1.2 Initialize array a 1.3 Execute actions 2.1 Define outputArray function 3.1 Define compareIntegers function 4.1 Set BODY to call start when page loaded
39
Script Output
40
12.8 Searching Arrays: Linear Search and Binary Search
When working with large amounts of data May be necessary to determine whether an array contains a value that matches a certain key value Searching – process of locating particular element value in an array Two searching techniques Linear Binary
41
12.8 Searching Arrays: Linear Search and Binary Search (II)
Linear searching Compares each element in an array with a search key Goes in order of elements in array If array unsorted, just as likely value will be found in first element as the last element Works well for small arrays or unsorted arrays Inefficient for large arrays
42
1.1 Create array a and fill with integer values
1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> 2 <HTML> 3 <!-- Fig : LinearSearch.html --> 4 5 <HEAD> 6 <TITLE>Linear Search of an Array</TITLE> 7 8 <SCRIPT LANGUAGE = "JavaScript"> 9 var a = new Array( 100 ); // create an Array 10 11 // fill Array with even integer values from 0 to 198 12 for ( var i = 0; i < a.length; ++i ) a[ i ] = 2 * i; 14 15 // function called when "Search" button is pressed 16 function buttonPressed() 17 { var searchKey = searchForm.inputVal.value; 19 // Array a is passed to linearSearch even though it // is a global variable. Normally an array will // be passed to a method for searching. var element = linearSearch( a, parseInt( searchKey ) ); 24 if ( element != -1 ) searchForm.result.value = "Found value in element " + element; else searchForm.result.value = "Value not found"; 30 } 1.1 Create array a and fill with integer values 2.1 define buttonPressed function 2.2 Initialize variables to inputted values 2.3 Set if/else structure for result output
43
3.1 Define linearSearch function
31 32 // Search "theArray" for the specified "key" value 33 function linearSearch( theArray, key ) 34 { for ( var n = 0; n < theArray.length; ++n ) if ( theArray[ n ] == key ) return n; 38 return -1; 40 } 41</SCRIPT> 42 43</HEAD> 44 45<BODY> 46<FORM NAME = "searchForm"> 47 <P>Enter integer search key<BR> 48 <INPUT NAME = "inputVal" TYPE = "text"> 49 <INPUT NAME = "search" TYPE = "button" VALUE = "Search" ONCLICK = "buttonPressed()"><BR></P> 51 52 <P>Result<BR> 53 <INPUT NAME = "result" TYPE = "text" SIZE = "30"></P> 54</FORM> 55</BODY> 56</HTML> 3.1 Define linearSearch function 3.2 Set search action 3.3 Return result 4.1 Open HTML FORM 4.2 Insert INPUT elements 4.4 Insert button and define ONCLICK action 4.3 Close FORM
44
Script Outputs
45
12.8 Searching Arrays: Linear Search and Binary Search (III)
Binary Searching Locates middle element Compares search key with middle element If they are equal, subscript of middle element returned Otherwise, algorithm sees if search key is higher or lower than middle value Searches upper or lower half of array (subarray) depending on search key location Continues same process until search key equals middle value of subarray or one element remains that is not equal to search key
46
12.8 Searching Arrays: Linear Search and Binary Search (IV)
Binary Searching (II) Worst scenario: Maximum number of comparisons is the exponent of the first power of 2 greater than the number of elements in the array Example: If array has 60 elements- 26 = 64, therefore maximum 6 comparisons Requires a sorted array in order to work
47
1.1 Create and assign element values for array a
1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> 2 <HTML> 3 <!-- Fig : BinarySearch.html --> 4 1.1 Create and assign element values for array a 2.1 Define buttonPressed function 2.2 Initialize variables 2.3 Call binarySearch function 2.4 Print results – if search key found 5 <HEAD> 6 <TITLE>Binary Search of an Array</TITLE> 7 8 <SCRIPT LANGUAGE = "JavaScript"> 9 var a = new Array( 15 ); 10 11 for ( var i = 0; i < a.length; ++i ) a[ i ] = 2 * i; 13 14 // function called when "Search" button is pressed 15 function buttonPressed() 16 { var searchKey = searchForm.inputVal.value; 18 searchForm.result.value = "Portions of array searched\n"; 21 // Array a is passed to binarySearch even though it // is a global variable. This is done because normally // an array is passed to a method for searching. var element = binarySearch( a, parseInt( searchKey ) ); 26 if ( element != -1 ) searchForm.result.value += "\nFound value in element " + element;
48
2.5 Print results – if search key not found
searchForm.result.value += "\nValue not found"; 32 } 33 34 // Binary search 35 function binarySearch( theArray, key ) 36 { var low = 0; // low subscript var high = theArray.length - 1; // high subscript var middle; // middle subscript 40 while ( low <= high ) { middle = ( low + high ) / 2; 43 // The following line is used to display the part // of theArray currently being manipulated during // each iteration of the binary search loop. buildOutput( theArray, low, middle, high ); 48 if ( key == theArray[ middle ] ) // match return middle; else if ( key < theArray[ middle ] ) high = middle - 1; // search low end of array else low = middle + 1; // search high end of array } 56 return -1; // searchKey not found 58 } 59 else 2.5 Print results – if search key not found 3.1 Define binarySearch function 3.2 Initialize variables 3.3 Use while structure to reiterate search until result returned 3.4 Call buildOutput function 3.5 Test to see if search key matched 3.6 Return result
49
4.1 Define buildOutput function
61 // part of the array being processed. 62 function buildOutput( theArray, low, mid, high ) 63 { for ( var i = 0; i < theArray.length; i++ ) { if ( i < low || i > high ) searchForm.result.value += " "; else if ( i == mid ) // mark middle element in output searchForm.result.value += a[ i ] + ( theArray[ i ] < 10 ? "* " : "* " ); else searchForm.result.value += a[ i ] + ( theArray[ i ] < 10 ? " " : " " ); } 74 searchForm.result.value += "\n"; 76 } 77</SCRIPT> 78 79</HEAD> 80 81<BODY> 82<FORM NAME = "searchForm"> 83 <P>Enter integer search key<BR> 84 <INPUT NAME = "inputVal" TYPE = "text"> 85 <INPUT NAME = "search" TYPE = "button" VALUE = "Search" ONCLICK = "buttonPressed()"><BR></P> 87 <P>Result<BR><TEXTAREA NAME = "result" ROWS = "7" COLS = "60"> </TEXTAREA></P> 89</FORM> 90</BODY> 91</HTML> 60 // Build one row of output showing the current 4.1 Define buildOutput function 4.2 Set structure actions to output element values searched this iteration 5.1 Open HTML FORM 5.2 Insert and define INPUT elements 5.3 Insert button and set ONCLICK action 5.4 Close FORM
50
Script Output 1
51
Script Output 2
52
12.9 Multiple-Subscripted Arrays
Multiple-Subscripted Arrays with two subscripts Often represent tables of values consisting of info arranged in rows and columns Double-subscripted array (or two-dimensional arrays) Require two subscripts to identify a particular element First subscript identifies element’s row Second subscript identifies element’s column m-by-n array An array with m rows and n columns
53
12.9 Multiple-Subscripted Arrays (II)
Double-scripted array with three rows and four columns a[0][0] a[0][1] a[1][0] a[1][1] a[2][0] a a[0][2] a[1][2] a[0][3] a[1][3] a[2][2] a[2][3] [2] [1] Column 3 Column 0 Column 2 Column 1 Row 0 Row 1 Row 2 Column subscript Row subscript Array name
54
12.9 Multiple-Subscripted Arrays (III)
Initialization Declared like a single-scripted array Double scripted array b with two rows and two columns could be declared and initialized with var b = [ [ 1, 2 ], [ 3, 4, 5 ] ]; Compiler determines number of elements in row/column By counting number of initializer values in sub-initializer list for that row/column Can have a different number of columns in each row for and for/in loops used to traverse the arrays Manipulate every element of the array
55
1.3 Call outputArray function for each array
1 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> 2 <HTML> 3 <!-- Fig : InitArray.html --> 4 1.1 Define start function 1.2 Initialize and set element values for multidimensional arrays array1 and array2 1.3 Call outputArray function for each array 5 <HEAD> 6 <TITLE>Initializing Multidimensional Arrays</TITLE> 7 8 <SCRIPT LANGUAGE = "JavaScript"> 9 function start() 10 { var array1 = [ [ 1, 2, 3 ], // first row [ 4, 5, 6 ] ]; // second row var array2 = [ [ 1, 2 ], // first row [ 3 ], // second row [ 4, 5, 6 ] ]; // third row 16 outputArray( "Values in array1 by row", array1 ); outputArray( "Values in array2 by row", array2 ); 19 } 20
56
2.1 Define outputArray function
} 32 document.writeln( "</TT>" ); 34 } 35 </SCRIPT> 36 37 </HEAD><BODY ONLOAD = "start()"></BODY> 38 </HTML> 21 function outputArray( header, theArray ) 22 { document.writeln( "<H2>" + header + "</H2><TT>" ); 24 for ( var i in theArray ) { 26 for ( var j in theArray[ i ] ) document.write( theArray[ i ][ j ] + " " ); 29 document.writeln( "<BR>" ); 2.1 Define outputArray function 2.2 Print header 2.3 Use nested for/in structures to traverse the arrays and output their contents 3.1 Set BODY element ONCLICK action
57
Script Output
58
12.9 Multiple-Subscripted Arrays (IV)
Different array manipulations using for and for/in: for ( int col = 0; col < a[ 2 ].length; ++col ) a[ 2 ][ col ] = 0; identical to for ( var col in a[ 2 ] ) a[ 2 ][ col ] = 0 Both statements set all elements in third row of array a to zero
59
12.9 Multiple-Subscripted Arrays (IV)
Different array manipulations using for and for/in var total = 0; for (var row = 0; row < a.length; ++row ) for (var col = 0; col < a[ row ].length; ++col ) total += a[ row ][ col ]; identical to for (var row in a ) for (var col in a[ row ] ) Both statements total the elements of the array, one row at a time
60
1.2 Initialize and set element values for array grades
1 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> 2 <HTML> 3 <!-- Fig : DoubleArray.html --> 4 5 <HEAD> 6 <TITLE>Double-subscripted Array Example</TITLE> 7 8 <SCRIPT LANGUAGE = "JavaScript"> 9 function start() 10 { var grades = [ [ 77, 68, 86, 73 ], [ 96, 87, 89, 81 ], [ 70, 90, 86, 81 ] ]; 14 document.writeln( "<PRE>" ); outputArray( grades ); 17 document.writeln( "\n\nLowest grade: " + minimum( grades ) + "\nHighest grade: " + maximum( grades ) ); 21 // calculate average for each student (i.e., each row) for ( var i in grades ) document.write( "\nAverage for student " + i + " is " + average( grades[ i ] ) ); 26 document.writeln( "</PRE>" ); 28 } 29 1.1 Define start function 1.2 Initialize and set element values for array grades 1.3 Call outputArray function 1.4 Call and display minimum function 1.5 Call and display maximum function 1.6 Call and display average function
61
2.1 Define minimum function
31 function minimum( grades ) 32 { var lowGrade = 100; 34 for ( var i in grades ) for ( var j in grades[ i ] ) if ( grades[ i ][ j ] < lowGrade ) lowGrade = grades[ i ][ j ]; 39 return lowGrade; 41 } 42 43 // find the maximum grade 44 function maximum( grades ) 45 { var highGrade = 0; 47 for ( var i in grades ) for ( var j in grades[ i ] ) if ( grades[ i ][ j ] > highGrade ) highGrade = grades[ i ][ j ]; 52 return highGrade; 54 } 55 30 // find the minimum grade 2.1 Define minimum function 2.2 Use nested for/in structures to calculate and return lowest grade 3.1 Define maximum function 3.2 Use nested for/in structures to calculate and return highest grade
62
4.1 Define average function
56 // determine the average grade for a particular 57 // student (or set of grades) 58 function average( setOfGrades ) 59 { var total = 0; 4.1 Define average function 4.2 Use for/in structure to return average grade for given student 5.1 Define outputArray function 5.2 Use nested for/in structures to output entire grades array 6.1 Set BODY element ONCLICK action 61 for ( var i in setOfGrades ) total += setOfGrades[ i ]; 64 return total / setOfGrades.length; 66 } 67 68 // output grades 69 function outputArray( grades ) 70 { document.write( " " ); // align heads 72 for ( var i in grades[ 0 ] ) document.write( "[" + i + "] " ); 75 for ( var i in grades ) { document.write( "<BR>grades[" + i + "] " ); 78 for ( var j in grades[ i ] ) document.write( grades[ i ][ j ] + " " ); } 82 } 83 </SCRIPT> 84 85 </HEAD><BODY ONLOAD = "start()"></BODY> 86 </HTML>
63
Script Output
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.