CS 112 Introduction to Programming - PowerPoint PPT Presentation

1 / 66
About This Presentation
Title:

CS 112 Introduction to Programming

Description:

You can access each character of a string using [ ], e.g. ... int, char, byte, float, double, string, e.g., int x = 45; double y = 45.12; ... – PowerPoint PPT presentation

Number of Views:36
Avg rating:3.0/5.0
Slides: 67
Provided by: Richar9
Category:

less

Transcript and Presenter's Notes

Title: CS 112 Introduction to Programming


1
CS 112 Introduction to Programming
  • Lecture 19
  • Arrays Examples and Parameter Passing
  • Http//zoo.cs.yale.edu/classes/cs112/

2
Outline
  • Examples
  • Command line array
  • Strings as arrays
  • Using array elements as counters
  • Parameter passing of arrays

3
Review Arrays
  • An array stores multiple elements of the same
    type
  • Refer to particular element in the array by
    position number
  • In C, an array behaves very much like an object
  • declaration and instantiation are like objects
  • declare an array variable
  • create an array using new
  • make a variable a reference of an array
  • parameter passing is similar to objects
  • an array has the Length property

4
Example 1 Command-Line Arguments
  • The signature of the Main method indicates that
    it takes an array of string as parameter
  • These values come from command-line arguments
    that are provided when the program is invoked
  • For example, the following invocation of the
    interpreter passes an array of three string
    objects into Main
  • C\gt Calculator 2 3
  • These strings are stored at positions 0-2 of the
    parameter
  • See Calculator.cs
  • To set command line if use command window, see
    above if use VS, Project-gtCalculator
    Properties-gtConfiguration Properties-gtDebugging-gtC
    ommand Line Arguements

5
Example 2 strings as Arrays
  • You can use a string as an array
  • You can access the length of a string using the
    Length property
  • You can access each character of a string using
    , e.g.,string resp Console.ReadLine().ToUpper
    ()for (int i 0 i lt resp.Length i)
    Console.Write( respi )

6
Examples Using the Elements of an Array as
Counters
  • Use array elements to keep track of number of
    occurrences of different values
  • Create an array with size of the number of
    possibilities
  • Each element of the array keeps track of the
    number of occurrences of one possibility
  • When a possibility occurs, increase the array
    element by one
  • For example, read a sequence of numbers between 1
    to 10 until user inputs 0 keeps track of number
    of occurrences of 1 to 10int
    counters10int numwhile ( (numInt32.Parse(
    Console.ReadLine() )) ! 0) countersnum

7
StudentPoll.cs
  • 1 // Fig. 7.7 StudentPoll.cs
  • 2 // A student poll program.
  • 3
  • 4 using System
  • 5 using System.Windows.Forms
  • 6
  • 7 class StudentPoll
  • 8
  • 9 // main entry point for application
  • 10 static void Main( string args )
  • 11
  • 12 int responses 1, 2, 6, 4, 8, 5,
    9, 7, 8, 10, 1,
  • 13 6, 3, 8, 6, 10, 3, 8, 2, 7, 6, 5,
    7, 6, 8, 6, 7,
  • 14 5, 6, 6, 5, 6, 7, 5, 6, 4, 8, 6, 8,
    10
  • 15
  • 16 int frequency new int 11
  • 17 string output ""
  • 18
  • 19 // increment the frequency for each
    response

Declare and initialize integer array responses
Declare and allocate integer array frequency
For every element in responses, increment the
frequency element that corresponds to the answer
Output the number of times each response appeared
8
Example Die Rolling Program
  • Example Use the value of rolling the dice as the
    subscript for the array
  • Increment the corresponding array element when a
    die value is rolled

9
RollDie.cs
  • 1 // Fig. 7.6 RollDie.cs
  • 2 // Rolling 12 dice.
  • 3
  • 4 using System
  • 5 using System.Drawing
  • 6 using System.Collections
  • 7 using System.ComponentModel
  • 8 using System.Windows.Forms
  • 9 using System.Data
  • 10 using System.IO
  • 11
  • 12 public class RollDie System.Windows.Forms.F
    orm
  • 13
  • 14 private System.Windows.Forms.Button
    rollButton
  • 15
  • 16 private System.Windows.Forms.RichTextBox
    displayTextBox
  • 17
  • 18 private System.Windows.Forms.Label
    dieLabel1
  • 19 private System.Windows.Forms.Label
    dieLabel2

Create a Random object
Declare an integer array frequency and allocate
it enough memory to hold 7 integers
10
RollDie.cs
  • 36 public RollDie()
  • 37
  • 38 InitializeComponent()
  • 39
  • 40
  • 41 // Visual Studio .NET generated code
  • 42
  • 43 STAThread
  • 44 static void Main()
  • 45
  • 46 Application.Run( new RollDie() )
  • 47
  • 48
  • 49 private void rollButton_Click(
  • 50 object sender, System.EventArgs e )
  • 51
  • 52 // pass the labels to a method that
    will
  • 53 // randomly assign a face to each die
  • 54 DisplayDie( dieLabel1 )

11
RollDie.cs
  • 71
  • 72 displayTextBox.Text
    "Face\tFrequency\tPercent\n"
  • 73
  • 74 // output frequency values
  • 75 for ( int x 1 x lt frequency.Length
    x )
  • 76
  • 77 displayTextBox.Text x "\t"
  • 78 frequency x "\t\t"
    String.Format( "0N",
  • 79 frequency x / total 100 )
    "\n"
  • 80
  • 81
  • 82 // end Main
  • 83
  • 84 // simulates roll, display proper
  • 85 // image and increment frequency
  • 86 public void DisplayDie( Label dieLabel )
  • 87
  • 88 int face randomNumber.Next( 1, 7 )
  • 89

Get a random number from 1 to 6
Display die image corresponding to the number
rolls
12
Outline
  • Admin. and review
  • Examples
  • Command line array
  • strings as arrays
  • Using array elements as counters
  • Parameter passing of arrays

13
Recall Two Types of Variables
  • A variable represents a cell in memory
  • Value type
  • int, char, byte, float, double, string, e.g.,int
    x 45double y 45.12
  • A value type variable stores a value of the type
    of the variable in the memory
  • Reference type
  • A variable that stores object or array actually
    stores a reference to an object or array,
    e.g.,Time3 t1t1 new Time3(11, 45, 59)
  • A reference is a location in computers memory
    where the object or array itself is stored

x
-45
y
-45.12
t1
14
Implications of the Two Types of Variables
  • An assignment of one value variable toanother
    value variable copies the value, e.g.,int x
    45double y 45.12int zz x
  • An assignment of one reference variable
    toanother reference variable copies the
    reference, e.g.,Time3 t1t1 new Time3(11, 45,
    59)Time3 t2t2 t1

x
-45
y
-45.12
t1
15
Implications of the Two Types of Variables
  • Change the value of one value variablewill
    change the otherint x 45double y
    45.12int zz xx 23
  • Change the content (state) by one reference may
    affect another reference variableTime3 t1t1
    new Time3(1, 2, 3)Time3 t2t2
    t1t2.SetTime(22, 22, 22)

x
-45
23
y
-45.12
t1
16
Calling a Method Value Type
  • Each time a method is called, the value of the
    actual arguments in the invocation are copied
    into the formal arguments
  • Modifications to formal arguments will not affect
    actual arguments

int num SquareSum (2, 3)
17
Calling a Method Value Type
int n1 2
int n2 3
int num SquareSum (n1, n2)
18
Calling a Method Value Type
  • Even if formal arguments and actual arguments
    have the same name, modifications to formal
    arguments in a method will not affect actual
    arguments

int num1 2
int num2 3
int num SquareSum (num1, num2)
19
Calling a Method Value Type to Ref
  • If a formal argument is ref (or out), then the
    formal argument and the actual argument are
    aliases of each other

int n1 2
int n2 3
int num SquareSum (ref n1, ref n2)
20
Passing Arrays by Value and by Reference
  • Passing value types to methods
  • A copy of the variable is made
  • Any changes to variable in method do not affect
    the original variable
  • Passing reference types to methods
  • A copy of the reference to the object/array is
    made
  • Any changes to the reference in the method do not
    affect the original variable
  • Any changes to the contents of the object/array
    in the method, do affect the object/array outside
    the method

21
Arrays as Parameters
  • Like any other object, the reference to the array
    is passed, making the formal and actual
    parameters aliases of each other
  • Changing an array element in the method changes
    the original
  • An array element can be passed to a method as
    well, and follow the parameter passing rules of
    that element's type

22
PassArray.cs
  • 1 // Fig. 7.8 PassArray.cs
  • 2 // Passing arrays and individual elements to
    methods.
  • 3 using System
  • 4 using System.Drawing
  • 5 using System.Collections
  • 6 using System.ComponentModel
  • 7 using System.Windows.Forms
  • 8 using System.Data
  • 9
  • 10 public class PassArray System.Windows.Forms
    .Form
  • 11
  • 12 private System.Windows.Forms.Button
    showOutputButton
  • 13 private System.Windows.Forms.Label
    outputLabel
  • 14
  • 15 // Visual Studio .NET generated code
  • 16
  • 17 STAThread
  • 18 static void Main()
  • 19

23
PassArray.cs
  • 36
  • 37 outputLabel.Text
  • 38 "\n\nThe values of the modified
    array are\n\t"
  • 39
  • 40 // display elements of array a
  • 41 for ( int i 0 i lt a.Length i )
  • 42 outputLabel.Text " " a i
  • 43
  • 44 outputLabel.Text "\n\nEffects of
    passing array "
  • 45 "element call-by-value\n\na 3
    before "
  • 46 "ModifyElement " a 3
  • 47
  • 48 // array element passed call-by-value
  • 49 ModifyElement( a 3 )
  • 50
  • 51 outputLabel.Text
  • 52 "\na 3 after ModifyElement "
    a 3
  • 53
  • 54

24
PassArray.csProgram Output
  • 70 e 2
  • 71
  • 72 outputLabel.Text
  • 73 "\nvalue calculated in
    ModifyElement " e
  • 74
  • 75

25
ArrayReferenceTest.cs
  • 1 // Fig. 7.9 ArrayReferenceTest.cs
  • 2 // Testing the effects of passing array
    references
  • 3 // by value and by reference.
  • 4 using System
  • 5 using System.Drawing
  • 6 using System.Collections
  • 7 using System.ComponentModel
  • 8 using System.Windows.Forms
  • 9 using System.Data
  • 10
  • 11 public class ArrayReferenceTest
    System.Windows.Forms.Form
  • 12
  • 13 private System.Windows.Forms.Label
    outputLabel
  • 14 private System.Windows.Forms.Button
    showOutputButton
  • 15
  • 16 STAThread
  • 17 static void Main()
  • 18
  • 19 Application.Run( new
    ArrayReferenceTest() )

26
ArrayReferenceTest.cs
  • 36
  • 37 // print contents of firstArray
  • 38 for ( int i 0 i lt
    firstArray.Length i )
  • 39 outputLabel.Text firstArray i
    " "
  • 40
  • 41 // pass reference firstArray by value
    to FirstDouble
  • 42 FirstDouble( firstArray )
  • 43
  • 44 outputLabel.Text "\n\nContents of
    firstArray after "
  • 45 "calling FirstDouble\n\t"
  • 46
  • 47 // print contents of firstArray
  • 48 for ( int i 0 i lt
    firstArray.Length i )
  • 49 outputLabel.Text firstArray i
    " "
  • 50
  • 51 // test whether reference was changed
    by FirstDouble
  • 52 if ( firstArray firstArrayCopy )
  • 53 outputLabel.Text
  • 54 "\n\nThe references refer to the
    same array\n"

27
ArrayReferenceTest.cs
  • 71 // print contents of secondArray
    before method call
  • 72 for ( int i 0 i lt
    secondArray.Length i )
  • 73 outputLabel.Text secondArray i
    " "
  • 74
  • 75 SecondDouble( ref secondArray )
  • 76
  • 77 outputLabel.Text "\n\nContents of
    secondArray "
  • 78 "after calling SecondDouble\n\t"
  • 79
  • 80 // print contents of secondArray after
    method call
  • 81 for ( int i 0 i lt
    secondArray.Length i )
  • 82 outputLabel.Text secondArray i
    " "
  • 83
  • 84 // test whether reference was changed
    by SecondDouble
  • 85 if ( secondArray secondArrayCopy )
  • 86 outputLabel.Text
  • 87 "\n\nThe references refer to the
    same array\n"
  • 88 else
  • 89 outputLabel.Text

28
ArrayReferenceTest.cs Program Output
  • 106 // modify elements of array and change
    reference array
  • 107 // to refer to a new array
  • 108 void SecondDouble( ref int array )
  • 109
  • 110 // double each element's value
  • 111 for ( int i 0 i lt array.Length i
    )
  • 112 array i 2
  • 113
  • 114 // create new reference and assign it
    to array
  • 115 array new int 11, 12, 13
  • 116
  • 117

29
Backup Slides
30
Two-Dimensional Arrays
  • A one-dimensional array stores a simple list of
    values
  • A two-dimensional array can be thought of as a
    table of values, with rows and columns
  • A two-dimensional array element is referenced
    using two index values
  • To be precise, a two-dimensional array in C is
    an array of arrays
  • See TwoDArray

31
Multidimensional Arrays
  • An array can have as many dimensions as needed,
    creating a multidimensional array
  • Each dimension subdivides the previous one into
    the specified number of elements
  • Each array dimension has its own length constant
  • Because each dimension is an array of array
    references, the arrays within one dimension could
    be of different lengths

32
Multiple-Subscripted Arrays
  • Require two or more subscripts to identify a
    particular element
  • Arrays that req2uire two subscripts to identify
    an element are called double-subscripted arrays
  • Rectangular arrays
  • Often represent tables in which each row is the
    same size and each column is the same size
  • By convention, first subscript identifies the
    elements row and the second subscript the
    elements column
  • Jagged Arrays
  • Arrays of arrays
  • Arrays that compose jagged arrays can be of
    different lengths

33
Multiple-Subscripted Arrays
Fig. 7.13 Double-subscripted array with three
rows and four columns.
34
Multidimensional Arrays
  • An initializer list can be used to create and set
    up a multidimensional array
  • Each element in the list is itself an initializer
    list
  • Note that each array dimension has its own Length
    property
  • See SodaSurvey

35
TwoDimensionalArrays.cs
  • 1 // Fig. 7.14 TwoDimensionalArrays.cs
  • 2 // Initializing two-dimensional arrays.
  • 3 using System
  • 4 using System.Drawing
  • 5 using System.Collections
  • 6 using System.ComponentModel
  • 7 using System.Windows.Forms
  • 8 using System.Data
  • 9
  • 10 public class TwoDimensionalArrays
    System.Windows.Forms.Form
  • 11
  • 12 private System.Windows.Forms.Button
    showOutputButton
  • 13 private System.Windows.Forms.Label
    outputLabel
  • 14
  • 15 // Visual Studio .NET generated code
  • 16
  • 17 STAThread
  • 18 static void Main()
  • 19

36
TwoDimensionalArrays.cs Program
Output
  • 36
  • 37 // output values in array1
  • 38 for ( int i 0 i lt array1.GetLength(
    0 ) i )
  • 39
  • 40 for ( int j 0 j lt
    array1.GetLength( 1 ) j )
  • 41 outputLabel.Text array1 i, j
    " "
  • 42
  • 43 outputLabel.Text "\n"
  • 44
  • 45
  • 46 outputLabel.Text "\nValues in
    array2 by row are\n"
  • 47
  • 48 // output values in array2
  • 49 for ( int i 0 i lt array2.Length
    i )
  • 50
  • 51 for ( int j 0 j lt array2 i
    .Length j )
  • 52 outputLabel.Text array2 i
    j " "
  • 53
  • 54 outputLabel.Text "\n"

37
DoubleArray.cs
  • 1 // Fig. 7.15 DoubleArray.cs
  • 2 // Manipulating a double-subscripted array.
  • 3 using System
  • 4 using System.Drawing
  • 5 using System.Collections
  • 6 using System.ComponentModel
  • 7 using System.Windows.Forms
  • 8 using System.Data
  • 9
  • 10 public class DoubleArray
    System.Windows.Forms.Form
  • 11
  • 12 private System.Windows.Forms.Button
    showOutputButton
  • 13 private System.Windows.Forms.Label
    outputLabel
  • 14
  • 15 int grades
  • 16 int students, exams
  • 17
  • 18 // Visual Studio .NET generated code
  • 19

38
DoubleArray.cs
  • 35 students grades.Length //
    number of students
  • 36 exams grades 0 .Length //
    number of exams
  • 37
  • 38 // line up column headings
  • 39 outputLabel.Text "
    "
  • 40
  • 41 // output the column headings
  • 42 for ( int i 0 i lt exams i )
  • 43 outputLabel.Text "" i "
    "
  • 44
  • 45 // output the rows
  • 46 for ( int i 0 i lt students i )
  • 47
  • 48 outputLabel.Text "\ngrades" i
    " "
  • 49
  • 50 for ( int j 0 j lt exams j )
  • 51 outputLabel.Text grades i
    j " "
  • 52
  • 53

39
DoubleArray.cs
  • 63 // find minimum grade in grades array
  • 64 public int Minimum()
  • 65
  • 66 int lowGrade 100
  • 67
  • 68 for ( int i 0 i lt students i )
  • 69
  • 70 for ( int j 0 j lt exams j )
  • 71
  • 72 if ( grades i j lt lowGrade
    )
  • 73 lowGrade grades i j
  • 74
  • 75 return lowGrade
  • 76
  • 77
  • 78 // find maximum grade in grades array
  • 79 public int Maximum()
  • 80
  • 81 int highGrade 0

40
DoubleArray.cs Program Output
  • 93 // determine average grade for a
    particular student
  • 94 public double Average( int setOfGrades
    )
  • 95
  • 96 int total 0
  • 97
  • 98 for ( int i 0 i lt
    setOfGrades.Length i )
  • 99 total setOfGrades i
  • 100
  • 101 return ( double ) total /
    setOfGrades.Length
  • 102
  • 103
  • 104 // end class DoubleArray

41
Backup Slides
42
strings as Arrays
  • You can use a string as an array
  • You can access the length of a string using the
    Length property
  • You can access each character of a string using

43
StringConstructor.cs
  • 1 // Fig. 15.1 StringConstructor.cs
  • 2 // Demonstrating String class constructors.
  • 3
  • 4 using System
  • 5 using System.Windows.Forms
  • 6
  • 7 // test several String class constructors
  • 8 class StringConstructor
  • 9
  • 10 // The main entry point for the
    application.
  • 11 STAThread
  • 12 static void Main( string args )
  • 13
  • 14 string output
  • 15 string originalString, string1,
    string2,
  • 16 string3, string4
  • 17
  • 18 char characterArray
  • 19 'b', 'i', 'r', 't', 'h', ' ',
    'd', 'a', 'y'

String declarations
Allocate char array characterArray to contain
nine characters
Set string1 to reference the same string literal
String constructor takes a character array as
argument
String constructor takes a char array and the
starting point of the array and the length
Using string constructed with a character and an
int specifying number of times to repeat
character in the string
44
StringConstructor.csProgram Output
  • 33 MessageBox.Show( output, "String Class
    Constructors",
  • 34 MessageBoxButtons.OK,
    MessageBoxIcon.Information )
  • 35
  • 36 // end method Main
  • 37
  • 38 // end class StringConstructor

45
StringMethods.cs
  • 1 // Fig. 15.2 StringMethods.cs
  • 2 // Using the indexer, property Length and
    method CopyTo
  • 3 // of class String.
  • 4
  • 5 using System
  • 6 using System.Windows.Forms
  • 7
  • 8 // creates string objects and displays
    results of using
  • 9 // indexer and methods Length and CopyTo
  • 10 class StringMethods
  • 11
  • 12 // The main entry point for the
    application.
  • 13 STAThread
  • 14 static void Main( string args )
  • 15
  • 16 string string1, output
  • 17 char characterArray
  • 18
  • 19 string1 "hello there"

46
Outline
  • Arrays
  • Declaration and initialization of arrays
  • Arrays as objects the Length property
  • Examples
  • string
  • Command line array
  • Using arrays as counters
  • Parameter passing of arrays
  • Sorting and search
  • Multi-dimensional arrays and dynamic arrays

47
Sorting
  • Sorting is the process of arranging a list of
    items into an ascending order
  • Question Why is sorting useful?

48
Sorting Two Components
  • Defining order
  • Question how do you define order in Java?
  • An algorithm to change the order of elements in
    the array
  • Question how do you sort an array of elements?

3 9 6 1 2
49
Sorting Arrays
  • Sorting data is important in many applications
  • Bubble Sort array of size n
  • Make n passes through the array
  • For each pass, compare every pair of successful
    elements
  • If the first is larger then the second, swap the
    elements
  • Easy to program
  • Runs slowly
  • .NET Framework includes high-speed sorting
    capabilities

50
BubbleSorter.cs
  • 1 // Fig. 7.10 BubbleSorter.cs
  • 2 // Sorting an array's values into ascending
    order.
  • 3 using System
  • 4 using System.Drawing
  • 5 using System.Collections
  • 6 using System.ComponentModel
  • 7 using System.Windows.Forms
  • 8 using System.Data
  • 9
  • 10 public class BubbleSorter
    System.Windows.Forms.Form
  • 11
  • 12 private System.Windows.Forms.Button
    sortButton
  • 13 private System.Windows.Forms.Label
    outputLabel
  • 14
  • 15 // Visual Studio .NET generated code
  • 16
  • 17 STAThread
  • 18 static void Main()
  • 19

51
BubbleSorter.cs Program Output
  • 36 outputLabel.Text "\n\nData items in
    ascending order\n"
  • 37
  • 38 for ( int i 0 i lt a.Length i )
  • 39 outputLabel.Text " " a i
  • 40
  • 41 // end method sortButton_Click
  • 42
  • 43 // sort the elements of an array with
    bubble sort
  • 44 public void BubbleSort( int b )
  • 45
  • 46 for ( int pass 1 pass lt b.Length
    pass ) // passes
  • 47
  • 48 for ( int i 0 i lt b.Length - 1
    i ) // one pass
  • 49
  • 50 if ( b i gt b i 1 )
    // one comparison
  • 51 Swap( b, i )
    // one swap
  • 52
  • 53
  • 54 // swap two elements of an array

52
Insertion Sort
  • The approach of Insertion Sort
  • Pick any item and insert it into its proper place
    in a sorted sublist
  • repeat until all items have been inserted
  • In more detail
  • consider the first item to be a sorted sublist
    (of one item)
  • insert the second item into the sorted sublist,
    shifting items as necessary to make room to
    insert the new addition
  • insert the third item into the sorted sublist (of
    two items), shifting as necessary
  • repeat until all values are inserted into their
    proper position

53
Insertion Sort
  • An example
  • original 3 9 6 1 2
  • insert 9 3 9 6 1 2
  • insert 6 3 6 9 1 2
  • insert 1 1 3 6 9 2
  • insert 2 1 2 3 6 9
  • See SortGrades.java
  • See Sorts.java -- the insertionSort method

54
Selection Sort
  • The approach of Selection Sort
  • select one value and put it in its final place in
    the sort list
  • repeat for all other values
  • In more detail
  • find the smallest value in the list
  • switch it with the value in the first position
  • find the next smallest value in the list
  • switch it with the value in the second position
  • repeat until all values are placed

55
Selection Sort
  • An example
  • original 3 9 6 1 2
  • smallest is 1 1 9 6 3 2
  • smallest is 2 1 2 6 3 9
  • smallest is 3 1 2 3 6 9
  • smallest is 6 1 2 3 6 9
  • See SortGrades.java
  • See Sorts.java -- the selectionSort method

56
Sorting Objects
  • Integers have an inherent order, but the order of
    a set of objects must be defined by the person
    defining the class
  • Recall that a Java interface can be used as a
    type name and guarantees that a particular class
    has implemented particular methods
  • We can use the Comparable interface to develop a
    generic sort for a set of objects
  • See SortPhoneList
  • See Contact
  • See Sorts

57
Comparing Sorts
  • Both Selection and Insertion sorts are similar in
    efficiency
  • The both have outer loops that scan all elements,
    and inner loops that compare the value of the
    outer loop with almost all values in the list
  • Therefore approximately on the order of n2
    comparisons are made to sort a list of size n
  • We therefore say that these sorts are of order n2
  • Other sorts are more efficient order n log2 n
  • e.g., merge sort, or quick sort in average case
  • An interesting question how do you argue that
    order n log2 n is the best you can do?

58
Searching a Sorted Array with Binary Search
  • Array must be sorted
  • Eliminate half the search elements at each step
  • Algorithm
  • Locate middle element
  • Compare to search key
  • If they are equal the element has been found,
    return subscript of middle element
  • If the search key is less then the middle
    element, search the first half of the array
  • If the search key is greater then the middle
    element, search the second half of the array
  • Repeat above until search key is equal to the
    middle element, or the subarray to be searched is
    on element (in which case the search key is not
    in the array)

59
BinarySearchTest.cs
  • 1 // Fig. 7.12 BinarySearchTest.cs
  • 2 // Demonstrating a binary search of an
    array.
  • 3
  • 4 using System
  • 5 using System.Drawing
  • 6 using System.Collections
  • 7 using System.ComponentModel
  • 8 using System.Windows.Forms
  • 9 using System.Data
  • 10
  • 11 public class BinarySearchTest
    System.Windows.Forms.Form
  • 12
  • 13 private System.Windows.Forms.Label
    promptLabel
  • 14
  • 15 private System.Windows.Forms.TextBox
    inputTextBox
  • 16
  • 17 private System.Windows.Forms.Label
    resultLabel
  • 18 private System.Windows.Forms.Label
    displayLabel
  • 19 private System.Windows.Forms.Label
    outputLabel

60
BinarySearchTest.cs
  • 36
  • 37 // searches for an element by calling
  • 38 // BinarySearch and displaying results
  • 39 private void findButton_Click( object
    sender,
  • 40 System.EventArgs e )
  • 41
  • 42 int searchKey Int32.Parse(
    inputTextBox.Text )
  • 43
  • 44 // initialize display string for the
    new search
  • 45 outputLabel.Text "Portions of array
    searched\n"
  • 46
  • 47 // perform the binary search
  • 48 int element BinarySearch( a,
    searchKey )
  • 49
  • 50 if ( element ! -1 )
  • 51 displayLabel.Text "Found value in
    element "
  • 52 element
  • 53 else
  • 54 displayLabel.Text "Value not
    found"

61
BinarySearchTest.cs
  • 69 // the following line displays the
    portion
  • 70 // of the array currently being
    manipulated during
  • 71 // each iteration of the binary
    search loop
  • 72 BuildOutput( a, low, middle, high
    )
  • 73
  • 74 if ( key array middle ) //
    match
  • 75 return middle
  • 76 else if ( key lt array middle )
  • 77 high middle - 1 // search
    low end of array
  • 78 else
  • 79 low middle 1
  • 80
  • 81 // end BinarySearch
  • 82
  • 83 return -1 // search key not found
  • 84
  • 85 // end method BinarySearch
  • 86
  • 87 public void BuildOutput(

62
BinarySearchTest.cs Program Output
  • 99 else
  • 100 outputLabel.Text
  • 101 array i .ToString( "00" )
    " "
  • 102
  • 103
  • 104 outputLabel.Text "\n"
  • 105
  • 106 // end BuildOutput
  • 107
  • 108 // end class BinarySearchTest

63
BinarySearchTest.cs Program Output
64
ArrayList and Vector
  • An object of class ArrayList or Vector is similar
    to an array in that it stores multiple values
  • However, an array list or vector object
  • only stores objects
  • does not have the indexing syntax that arrays
    have
  • The methods of the ArrayList or Vector class are
    used to interact with the elements
  • They are part of the java.util package

65
ArrayList and Vector
  • An important difference between an array and an
    array list is that the later can be thought of as
    a dynamic, able to change its size as needed
  • Each array list initially has a certain amount of
    memory space reserved for storing elements
  • If an element is added that doesn't fit in the
    existing space, more room is automatically
    acquired

66
Question How to Deal with Dynamic Arrays
  • Another design of the previous problem, using the
    ArrayList class
  • See CDCollectionList
  • See TunesList
Write a Comment
User Comments (0)
About PowerShow.com