COPYRIGHT 2003: Dr. David Scanlan, CSUS OBJECTIVES: Explain the need for arrays. Coding an array....

26
COPYRIGHT 2003: Dr. David Scanlan, CSUS OBJECTIVES: • Explain the need for arrays. • Coding an array. •Basic algorithms: Largest, Smallest, Sum, Standard Deviation, Bubble Sort, Binary Search Arrays and Common Algorithms

Transcript of COPYRIGHT 2003: Dr. David Scanlan, CSUS OBJECTIVES: Explain the need for arrays. Coding an array....

COPYRIGHT 2003: Dr. David Scanlan, CSUS

OBJECTIVES:• Explain the need for arrays.• Coding an array.•Basic algorithms: Largest, Smallest, Sum, Standard Deviation, Bubble

Sort, Binary Search

Arrays and Common Algorithms

COPYRIGHT 2003: Dr. David Scanlan, CSUS Arrays (An Array of Houses)

MainStreet(0)

MainStreet(1)

MainStreet(2)

MainStreet(3)

MainStreet(4)

MainStreet(5)

MainStreet(6)

ARRAY OF HOUSES1. The array name is “MainStreet”2. The addresses range from MainStreet(0) to

MainStreet(6).In programming we use the word “Index”when we refer to a particular memory addresswithin the array. Here the indexes range from 0to 6.

3. Note that the houses are all the same “type”.The houses only differ in size.In programming, an array must contain the same “type” of data. The data can only differin size. For example, an array with an integer data type can only contain integervalues that can differ in size.

4. The size of this array is 7, and the address (index) starts with 0.Array indexes in Visual Basic.Net always start with 0.

WHEN WE DISCUSS ARRAYS IN THE NEXT SLIDESYOU NEED TO KEEP THIS ANALOGY IN MIND. THE ANALOGY IS A GOOD ONE FOR UNDERSTANDING ARRAYS IN PROGRAMMING.

COPYRIGHT 2003: Dr. David Scanlan, CSUS

ARRAYS are one of the most useful ways in which to hold data and manipulate data. ARRAYS are found in every computer language. They are often used for sorting records and for searching through records for particular one. We will use an array for processing data.

In this set of slides we will enter numeric values into an array. Then we will:1. Search for the largest number.2. Search for the smallest number.3. Search for the range of the numbers.4. Calculate the sum of the numbers in the

array.

Arrays and Common Algorithms

COPYRIGHT 2003: Dr. David Scanlan, CSUS

Fortunately, all computer languages have a way of structuring data called an ARRAY. With this way of structuring data we can easily move through this structure of data to do almost any thing we want.

Arrays and Common Algorithms

202510 515

Array(0)Array(1)Array(2)Array(3)Array(4)

Array in memory

Arraypositions:

COPYRIGHT 2003: Dr. David Scanlan, CSUS Arrays and Common Algorithms

202510 515

Array(0)Array(1)Array(2)Array(3)Array(4)

Array in memory

ArrayLocations:

CHARACTERISTICS OF AN ARRAY:1. An array is a set of memory locations into which we can store and read values.2. An array is given ONE name, but has MANY locations.3. We access these locations by using the ARRAY NAME followed by a "SUBSCRIPT".

(Another name for subscript is "index".)4. You can put as many locations as you want in the array...within reason.5. You can set it up with any type of data.6. You can use any legal VB.Net name for the array.7. An array is treated like any variable, but you must use a subscript (index) to access

its locations in memory. An array's first location's subscript is always 0.8. How to code it:

Dim Array(4) As Integer

Array(0) = 20Array(1) = 25Array(2) = 10Array(3) = 5Array(4) = 15

This array is declared:1. With the name "array".2. With 5 locations.3. With Integer as its data type.

Subscripts using numeric literal constants, but you USUALLY use a INTEGER VARIABLE NAME for the subscript as you will soon see.

Assigning 5 numbers to the array.

COPYRIGHT 2003: Dr. David Scanlan, CSUS

GO TO PROG07-IN-CLASS:

Run this program and:1. Search for the largest number.2. Search for the smallest number.3. Search for the range of the numbers.4. Calculate the sum of the numbers in the

array.

Flowchart the algorithms in PROG07-IN-CLASS.

Arrays and Common Algorithms

COPYRIGHT 2003: Dr. David Scanlan, CSUS

GUI for program

COPYRIGHT 2003: Dr. David Scanlan, CSUS

IMPORTANT

• You will need to modify the algorithms in these notes for assignment 05

COPYRIGHT 2003: Dr. David Scanlan, CSUS Arrays and Common Algorithms

Dim Array(4) As Integer Dim J As Integer = 0 Private Sub btnPutNumberIntoArray_Click(ByVal sender As System.Object, _

ByVal e As System.EventArgs) Handles btnPutNumberIntoArray.Click

Array(J) = CInt(txtNumbers.Text) J = J + 1 txtNumbers.Clear() txtNumbers.Focus()

End Sub

Topic: Load array with numbers

ButtonPut Number In Array

J = J + 1

End Sub

Array(J ) = TextBox.TextTextBox.ClearTextBox.Focus

Note the array and J are at the module level.

Array(0)

Array(1)

Array(2)

Array(3)

Array(4)

J

COPYRIGHT 2003: Dr. David Scanlan, CSUS

Private Sub btnDisplayNumbersInArray_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles txtDisplayNumbersInArray.Click

txtDisplayNumbers.Clear()

For J = 0 To 4

txtDisplayNumbers.Text = txtDisplayNumbers.Text & CStr(Array(J)) & _ControlChars.NewLine

Next

End Sub

Arrays and Common Algorithms

Topic: Reading and displaying array values.

ButtonDisplay All Numbers

End Sub

While J <= 4

J = 0

Display Array Numbers

J = J + 1

True

False

Clear Display

Remember Array and J have already been declared as module level.

Array(0)

Array(1)

Array(2)

Array(3)

Array(4)

These numbers could be variables or constants

J

COPYRIGHT 2003: Dr. David Scanlan, CSUS Arrays and Common Algorithms

Topic: Find and display largest number.

Private Sub btnDisplayLargestNumber_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnDisplayLargestNumber.Click

Dim Largest As Integer Largest = Array(0) For J = 1 To 4 If Array(J) > Largest Then Largest = Array(J) End If Next txtDisplayNumbers.Text = CStr(Largest)

End Sub

ButtonDisplay Largest Number

End Sub

While J <= 4

J = 1

Largest = Array(0)

Display Largest Number

IfArray(j) > Largest

Largest = Array(J )

J = J + 1

True

False

Array(0)

Array(1)

Array(2)

Array(3)

Array(4)

J

Largest

COPYRIGHT 2003: Dr. David Scanlan, CSUS Arrays and Common Algorithms

Topic: Find and display smallest number.

Private Sub btnDisplaySmallestNumber_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnDisplaySmallestNumber.Click

Dim Smallest As Integer Smallest = Array(0) For J = 1 To 4 If Array(J) < Smallest Then Smallest = Array(J) End If Next txtDisplayNumbers.Text = CStr(Smallest)

End Sub

ButtonDisplay Smallest Number

End Sub

While J <= 4

J = 1

Smallest = Array(0)

Display Smallest Number

IfArray(j) < Smallest

Smallest = Array(J )

J = J + 1

True

False

Array(0)

Array(1)

Array(2)

Array(3)

Array(4)

J

Smallest

COPYRIGHT 2003: Dr. David Scanlan, CSUS Arrays and Common Algorithms

Topic: Find and display range.

Private Sub btnDisplayRange_Click_1(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnDisplayRange.Click

Dim Smallest As Integer Dim Largest As Integer Smallest = Array(0) Largest = Array(0) For J = 1 To 4 If Array(J) < Smallest Then Smallest = Array(J) ElseIf Array(J) > Largest Then Largest = Array(J) End If Next txtDisplayNumbers.Text = _

CStr(Smallest) & " to " & CStr(Largest)

End Sub

ButtonDisplay Range

End Sub

While J <= 4

J = 1

Smallest = Array(0)Largest = Array(0)

Display Range Number

IfArray(j) < Smallest

Smallest = Array(J )

True

False

IfArray(J ) > Largest

Largest = Array(J )

J = J + 1

ThenElse

ThenElse

COPYRIGHT 2003: Dr. David Scanlan, CSUS Arrays and Common Algorithms

Topic: Find the sum of the numbers within an array.

Private Sub btnDisplaySumOfNumbers_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnDisplaySumOfNumbers.Click

Dim Sum As Integer For J = 0 To 4 Sum = Sum + Array(J) Next txtDisplayNumbers.Text = CStr(Sum)

End Sub

ButtonDisplay Array Sum

End Sub

While J <= 4

J = 0

Display Array Sum J = J + 1

False Sum = Sum + Array(J )

TrueArray(0)

Array(1)

Array(2)

Array(3)

Array(4)

J

Sum

COPYRIGHT 2003: Dr. David Scanlan, CSUS Arrays and Common Algorithms

Topic: Sort array using BUBBLE SORT algorithm. Slide 1/6.

'How it works: ' PASS-1 ' 5< 4 4 4 4 ' 4< 5< 3 3 3 ' 3 3< 5< 2 2 ' 2 2 2< 5< 1 ' 1 1 1 1< 5 <CORRECT POSITION> 'Compares = 4

'PASS-2 '4< 3 3 3 '3< 4< 2 2 '2 2< 4< 1 '1 1 1< 4 <CORRECT POSITION> '5 5 5 5 'Compares = 3

'PASS-3 '3< 2 2 '2< 3< 1 '1 1< 3 <CORRECT POSITION> '4 4 4 '5 5 5 'Compares = 2

'PASS-4 '2< 1 '1< 2 <CORRECT POSITION> '3 3 '4 4 '5 5 'Compares = 1

Largest value "bubbles" down into its correct position.

There is no need to compare again values that have "bubbled" into their correct position.

Start with these 5 numbersCompare two numbers, swap if necessary and move downward one position in the array.

COPYRIGHT 2003: Dr. David Scanlan, CSUS Arrays and Common Algorithms

Topic: Sort array using BUBBLE SORT algorithm. Slide 2/6.

'How it works: ' PASS-1 ' 5< 4 4 4 4 ' 4< 5< 3 3 3 ' 3 3< 5< 2 2 ' 2 2 2< 5< 1 ' 1 1 1 1< 5 <CORRECT POSITION> 'Compares = 4

'PASS-2 '4< 3 3 3 '3< 4< 2 2 '2 2< 4< 1 '1 1 1< 4 <CORRECT POSITION> '5 5 5 5 'Compares = 3

'PASS-3 '3< 2 2 '2< 3< 1 '1 1< 3 <CORRECT POSITION> '4 4 4 '5 5 5 'Compares = 2

'PASS-4 '2< 1 '1< 2 <CORRECT POSITION> '3 3 '4 4 '5 5 'Compares = 1

Things to note about this sort:1. At the end of each pass, the largest unsorted value "bubbles" down to its correct position.

2. One less comparison is required during a pass, after each pass.

3. Maximum comparisons needed:C = (N/2) * (N-1)

(N/2) = Average number of comparisons per pass.

(N-1) = Maximum number of passes needed to sort list.

C = (5/2) * (5-1)C = (2.5) * (4)C = 10

4. Maximum number of passes needed to sort list.

Max Passes = N - 1 (N = Number of items.)Max Passes = 5 -1Max Passes = 4

Start with these 5 numbers

COPYRIGHT 2003: Dr. David Scanlan, CSUS Arrays and Common Algorithms

Topic: Sort array using BUBBLE SORT algorithm. Slide 3/6.

'How it works: ' PASS-1 ' 5< 4 4 4 4 ' 4< 5< 3 3 3 ' 3 3< 5< 2 2 ' 2 2 2< 5< 1 ' 1 1 1 1< 5 <CORRECT POSITION> 'Compares = 4

'PASS-2 '4< 3 3 3 '3< 4< 2 2 '2 2< 4< 1 '1 1 1< 4 <CORRECT POSITION> '5 5 5 5 'Compares = 3

'PASS-3 '3< 2 2 '2< 3< 1 '1 1< 3 <CORRECT POSITION> '4 4 4 '5 5 5 'Compares = 2

'PASS-4 '2< 1 '1< 2 <CORRECT POSITION> '3 3 '4 4 '5 5 'Compares = 1

Things to note about this sort:5. This is a worst case example. That is, the worst case for a bubble sort is when the list is in reverse order. By worst case, we mean the number of compares and passes needed to sort the list is at maximum.

6. The best case is when the list is already ordered.

7. The sort is good for a small number of items only. If over 20, use Shell or quick sorts.

8. It is often used to keep a list in order when the list has been modified by changing the order of just one or two items. In this case, the list can be very large.

Start with these 5 numbers

COPYRIGHT 2003: Dr. David Scanlan, CSUS Arrays and Common Algorithms

Topic: Sort array using BUBBLE SORT algorithm. Slide 4/6.

'How it works: ' PASS-1 ' 5< 4 4 4 4 ' 4< 5< 3 3 3 ' 3 3< 5< 2 2 ' 2 2 2< 5< 1 ' 1 1 1 1< 5 <CORRECT POSITION> 'Compares = 4

'PASS-2 '4< 3 3 3 '3< 4< 2 2 '2 2< 4< 1 '1 1 1< 4 <CORRECT POSITION> '5 5 5 5 'Compares = 3

'PASS-3 '3< 2 2 '2< 3< 1 '1 1< 3 <CORRECT POSITION> '4 4 4 '5 5 5 'Compares = 2

'PASS-4 '2< 1 '1< 2 <CORRECT POSITION> '3 3 '4 4 '5 5 'Compares = 1

Summary Remarks:1. When we start the algorithm at he top of the list and sort in ascending order, the larger values bubble downward.

2. When we start the algorithm at the bottom of the list and sort in ascending order, the smaller items bubble upward.

3. Some bubble sort algorithms do not terminate after a complete pass with no swaps. This method will cause a maximum number of comparisons to be made.

NOTE: Always terminate after one complete pass with no swaps.

4. Some bubble sort algorithms do not examine one less pair after each pass. This algorithm is to be avoided.

5. Our algorithm exits the sort if one complete pass has been made without a swap, and makes one less compare after each pass.

Start with these 5 numbers

COPYRIGHT 2003: Dr. David Scanlan, CSUS Arrays and Common Algorithms

Topic: Sort array using BUBBLE SORT algorithm. Slide 5/6.

ButtonStart Bubble Sort

UpperSub = 4SwapFlag = True

WhileSwapFlag = True

ANDUpperSub >= 1

J = 0SwapFlag = False

WhileJ <= UpperSub - 1

IfArray(J )

>Array(J + 1)

Temp = Array(J )Array(J ) = Array(J +1)Array(J +1) = TempSwapFlag = True

J = J + 1UpperSub = UpperSub - 1

End Bubble Sort

UpperSub: Last subscript used in sort.SwapFlag: True if swap occurs.J : Position in Array (Subscript)

True

True

Then

False

False

Else

Pass completed

Array(0)

Array(1)

Array(2)

Array(3)

Array(4)

UpperSub

J

SwapFlag

3

5

4

2

1

Pass 1

Temp

Pass 3

Pass 4Pass 2

Array(0)

Array(1)

Array(2)

Array(3)

Array(4)

COPYRIGHT 2003: Dr. David Scanlan, CSUS Arrays and Common Algorithms

Topic: Sort array using BUBBLE SORT algorithm. Slide 6/6.

Dim SwapFlag As Boolean Dim UpperSub As Integer 'Upper subscript used in the sort. Dim Temp As Integer 'Used to hold larger value temporarily during an exchange. UpperSub = 4 'The upper subscript is 4 in this case. SwapFlag = True 'Set to True so While Loop can begin.

While SwapFlag = True And UpperSub >= 1 'Sort stops if no swap or upper subscript = 0 J = 0 'Sets subscript to first location in array for beginning of pass. SwapFlag = False 'SwapFlag will stay False unless a swap is made. While J <= UpperSub - 1 'UpperSub is decrementing, thus loop stops sooner. If Array(J) > Array(J + 1) Then 'Decides if a swap in necessary. Temp = Array(J) 'Temporarily saves value in Array(J) during a swap. Array(J) = Array(J + 1) 'Makes lower value "bubble" up one position. Array(J + 1) = Temp 'Causes higher value to "bubble" down one position. SwapFlag = True 'Since a swap was made, flag must be set to True. End If J = J + 1 'Increases subscript by one, while working toward a pass. End While UpperSub = UpperSub - 1 'Pass completed. Go down one less item during compares. End While

COPYRIGHT 2003: Dr. David Scanlan, CSUS Arrays and Common Algorithms

Topic: Sort array using BUBBLE SORT algorithm. Slide 6/6.

Dim SwapFlag As BooleanDim UpperSub As Integer Dim Temp As Integer

UpperSub = 4 SwapFlag = True

While SwapFlag = True And UpperSub >= 1 J = 0

SwapFlag = False While J <= UpperSub - 1 If Array(J) > Array(J + 1) Then Temp = Array(J) Array(J) = Array(J + 1) Array(J + 1) = Temp SwapFlag = True End If J = J + 1 End While UpperSub = UpperSub - 1 End While

ButtonStart Bubble Sort

UpperSub = 4SwapFlag = True

WhileSwapFlag = True

ANDUpperSub >= 1

J = 0SwapFlag = False

WhileJ <= UpperSub - 1

IfArray(J )

>Array(J + 1)

Temp = Array(J )Array(J ) = Array(J +1)Array(J +1) = TempSwapFlag = True

J = J + 1UpperSub = UpperSub - 1

End Bubble Sort

UpperSub: Last subscript used in sort.SwapFlag: True if swap occurs.J : Position in Array (Subscript)

True

True

Then

False

False

Else

One pass completed.

COPYRIGHT 2003: Dr. David Scanlan, CSUS Arrays and Common Algorithms

Topic: Binary search algorithm.

'BINARY SEARCH '*******************************************************************************************************************************

' -- Before the search, the array must be sorted in ascending order. ' -- How it works: ' - Start from the middle of the array and check if we have found a match. ' If not, check to see if what we found is greater or lesser than the Search Key. ' If it is lesser, we can ignore all the values greater than and including) the middle value. ' If it is greater, we can ignore all the value less than and including the middle value. ' - The loop terminates when we find a match or when the Low subscript becomes ' greater than the High subscript. ' -- THIS SEARCH METHOD IS VERY FAST. '*******************************************************************************************************************************

BINARY SEARCH

COPYRIGHT 2003: Dr. David Scanlan, CSUS Arrays and Common Algorithms

Topic: BINARY SEARCH algorithm in pseudocode.

Dim Key As Integer ' Value being search for Dim Low As Integer 'Low subscript Dim High As Integer 'High subscript Dim Mid As Integer 'Middle subscript: Mid = High + Low \ 2

Key = 4 Low = 0 High = 4

While Low <= High Mid = (High + Low) \ 2 If Key = Array(Mid) Then txtDisplayNumbers.Text = "Search Key found at Array(" & Str(Mid) & ")" Low = High + 1 'Terminates loop ElseIf Key < Array(Mid) Then High = Mid - 1 ElseIf Key > Array(Mid) Then Low = Mid + 1 End If End While

If Key <> Array(Mid) Then txtDisplayNumbers.Text = "Search Key not found." End If

COPYRIGHT 2003: Dr. David Scanlan, CSUS Arrays and Common Algorithms

Topic: BINARY SEARCH algorithm

Low = 0High = 4

Key =

While Low <= High

Mid = (High + Low) \ 2

If Key = Array(Mid)

High = Mid - 1

ElseIfKey > Array(Mid)

Low = Mid + 1

ElseIfKey < Array(Mid)

Low = High + 1

End

Start

Search Key

FOUND

If Key = Array (Mid)

True

TrueFalse

False

True

True

False

False

Search Key

NOT FOUND

True

Array(0)

Array(1)

Array(2)

Array(3)

Array(4)

KEY LOW HIGH MID

1

2

3

4

5

COPYRIGHT 2003: Dr. David Scanlan, CSUS

IMPORTANT

• You will need to modify the algorithms in these notes for assignment 05

COPYRIGHT 2003: Dr. David Scanlan, CSUS

THE END

Arrays and Common Algorithms