42
CIS162AD - C# Arrays – Part 2 13_arrays_sorting.ppt

CIS162AD - C# Arrays – Part 2 13_arrays_sorting.ppt

Embed Size (px)

Citation preview

Page 1: CIS162AD - C# Arrays – Part 2 13_arrays_sorting.ppt

CIS162AD - C#

Arrays – Part 2

13_arrays_sorting.ppt

Page 2: CIS162AD - C# Arrays – Part 2 13_arrays_sorting.ppt

CIS162AD 2

Overview of Topics

Declaring Arrays Loading Arrays Processing Arrays Sorting Arrays Searching Arrays Parallel Arrays Multi-dimensional Arrays

Page 3: CIS162AD - C# Arrays – Part 2 13_arrays_sorting.ppt

CIS162AD 3

Array Processing

1. Declare Array2. Load Array

• After creating the array, data must be loaded.• Use arrayName.Length or arrayName.GetUpperBound(0) to

prevent out of range errors.• Note: Arrays can be declared and loaded with constant values.

3. Process Array• Use individual elements in calculations or as arguments.• Send entire arrays to procedures for processing.• Sort, Search, Display• Use a lot of For loops or For Each loops.

Page 4: CIS162AD - C# Arrays – Part 2 13_arrays_sorting.ppt

CIS162AD 4

Array Management If during execution, the subscript value referenced an element

past the end of the array, the program would throw a subscript out range exception (run-time error).

The programmer must make sure that the logic in the program does not allow the subscript to exceed the array size.

We can use some built in methods to manage arrays,arrayName.LengtharrayName.GetUpperBound(0)

For partially filled arrays we must count how many items are loaded and then use the count when processing the arrays.

Page 5: CIS162AD - C# Arrays – Part 2 13_arrays_sorting.ppt

CIS162AD 5

Array SubscriptdataType[ ] arrayName = new dataType[arraySize];

Arrays are allocated consecutive memory. Each element is referenced using a subscript. Subscript are integers. The number of elements that are created is arraySize. The first element in the array is referenced with a

value of zero [0]. The last element is referenced with a subscript value

of [arraySize – 1]. A subscript is also referred to as an index. Short variable names for subscripts are acceptable.

Page 6: CIS162AD - C# Arrays – Part 2 13_arrays_sorting.ppt

CIS162AD 6

Declare Array

//Arrays are declared at the class level, //so they can be referenced by all methods.

const int intARRAY_SIZE = 20;int[ ] cintTestScores = new int[intArraySize]; int cintNumberOfStudents;

//We can load up to 20 scores, but we will save //how many tests are actually loaded in

cintNumberOfStudents.

Page 7: CIS162AD - C# Arrays – Part 2 13_arrays_sorting.ppt

CIS162AD 7

Array Memory MapPosition Address Index Value

1 1010 [0] 0

2 1014 [1] 0

3 1018 [2] 0

4 1022 [3] 0

5 1026 [4] 0

6 1030 [5] 0

7 1034 [6] 0

… … … …

20 1086 [19] 0

Page 8: CIS162AD - C# Arrays – Part 2 13_arrays_sorting.ppt

CIS162AD 8

Loading Partially Filled Arrays//Loads Array with scores saved in a data file.private void btnLoadArray_Click( ){

FileStream studentFile = new FileStream("cs12ex.txt", FileMode.Open); StreamReader studentStreamReader = new StreamReader(studentFile);

int i = 0; //subscript initialized to zero while (studentStreamReader.Peek() != -1){ if (i < cintTestScores.Length) { cintTestScores[i] = int.Parse(studentStreamReader.ReadLine( ));

i ++; //Increment subscript by one } else { MessageBox.Show (“Array Size Exceeded”);

break; //Get of out of loop; Array is full. }}cintNumberOfStudents = i; //Save how many students were loadedstudentFile.Close( ); //Close file

}

cs12ex.txt

5040100301020

Page 9: CIS162AD - C# Arrays – Part 2 13_arrays_sorting.ppt

CIS162AD 9

Loaded ArraysPosition Address Index Value

1 1010 [0] 50

2 1014 [1] 40

3 1018 [2] 100

4 1022 [3] 30

5 1026 [4] 10

6 1030 [5] 20

7 1034 [6] 0

… … … …

20 1086 [19] 0

Page 10: CIS162AD - C# Arrays – Part 2 13_arrays_sorting.ppt

CIS162AD 10

Partially Filled Arrays

Up to 20 scores could be loaded, but only 6 scores are actually loaded.

When the array is not full, it is considered a partially filled array.

When processing arrays, we need to make sure we only process the number scores loaded.

The number of scores loaded were counted in the load routine, and the count was saved in cintNumberOfStudents.

Page 11: CIS162AD - C# Arrays – Part 2 13_arrays_sorting.ppt

CIS162AD 11

Sorting Arrays

Data is always being sorted. It is important that we understand how sorts work. There are various sort algorithms. We’ll only be looking at the simple selection sort. Selection Sort Algorithm:

– Find the lowest value in the array.

– Move it to the top of the array.

– Find the next lowest value, and move it to the 2nd position.

– Continue until the end of the array is reached.

Page 12: CIS162AD - C# Arrays – Part 2 13_arrays_sorting.ppt

CIS162AD 12

Sort Ascendingprivate void sortAscending(…){ int i, i2; int intMinScore, intMinSubscript, intHoldValue;

for (i = 0; i < cintNumberOfStudents - 1; i++) //-1 so we don’t all the way to the bottom {

intMinSubscript = i; intMinScore = cintTestScores[i]; for (i2 = i + 1; i2 < cintNumberOfStudents; i2++)

{ if {cintTestScore[i2] < intMinScore)

{ intMinSubscript = i2; intMinScore = intTestScores[i2]; } }

intHoldValue = cintTestScores[i]; //swap values cintTestScores[i] = cintTestScores[intMinSubscript]; cintTestScore[intMinSubscript] = intHoldValue; }}

Page 13: CIS162AD - C# Arrays – Part 2 13_arrays_sorting.ppt

CIS162AD 13

Sort Algorithm Demonstration

const int intARRAY_SIZE = 20;int[ ] cintTestScores = new int[intArraySize]; int cintNumberOfStudents;

Page 14: CIS162AD - C# Arrays – Part 2 13_arrays_sorting.ppt

CIS162AD 14

Declared Array - cintTestScoresAddress Subscript Value

1010 [0] 0

1014 [1] 0

1018 [2] 0

1022 [3] 0

1026 [4] 0

1030 [5] 0

1034 [6] 0

… … …

1086 [19] 0

Page 15: CIS162AD - C# Arrays – Part 2 13_arrays_sorting.ppt

CIS162AD 15

Load ArraySubscript Value

[0] 50

[1] 40

[2] 100

[3] 30

[4] 10

[5] 20

[6] 0

… …

[19] 0

Read 6 numbers from file and load them into array.

Numbers of Students = i

i = 6

Page 16: CIS162AD - C# Arrays – Part 2 13_arrays_sorting.ppt

CIS162AD 16

Sort Ascending 1st positionSubscript Value

[0] 50

[1] 40

[2] 100

[3] 30

[4] 10

[5] 20

[6] 0

… …

[19] 0

Move the value in the 1st position to holdValue = 50.

Find the lowest value and move it to the 1st position.

Move holdValue to the position that the lowest value was found, swap values.

Page 17: CIS162AD - C# Arrays – Part 2 13_arrays_sorting.ppt

CIS162AD 17

Sort Ascending 2nd positionSubscript Value

[0] 10

[1] 40

[2] 100

[3] 30

[4] 50

[5] 20

[6] 0

… …

[19] 0

Move the value in the 2nd position to holdValue = 40.

Find the next lowest value and move it to the 2nd position.

Move holdValue to the position that the lowest value was found.

Page 18: CIS162AD - C# Arrays – Part 2 13_arrays_sorting.ppt

CIS162AD 18

Sort Ascending 3rd positionSubscript Value

[0] 10

[1] 20

[2] 100

[3] 30

[4] 50

[5] 40

[6] 0

… …

[19] 0

Move the value in the 3rd position to holdValue = 100.

Find the next lowest value and move it to the 3rd position.

Move holdValue to the position that the lowest value was found.

Page 19: CIS162AD - C# Arrays – Part 2 13_arrays_sorting.ppt

CIS162AD 19

Sort Ascending 4th positionSubscript Value

[0] 10

[1] 20

[2] 30

[3] 100

[4] 50

[5] 40

[6] 0

… …

[19] 0

Move the value in the 4th position to holdValue = 100.

Find the next lowest value and move it to the 4th position.

Move holdValue to the position that the lowest value was found.

Page 20: CIS162AD - C# Arrays – Part 2 13_arrays_sorting.ppt

CIS162AD 20

Sort Ascending 5th positionSubscript Value

[0] 10

[1] 20

[2] 30

[3] 40

[4] 50

[5] 100

[6] 0

… …

[19] 0

Move the value in the 5th position to holdValue = 50.

A lower value than 50 will not be found, but the comparison must still be made.

Page 21: CIS162AD - C# Arrays – Part 2 13_arrays_sorting.ppt

CIS162AD 21

Sort Ascendingprivate void sortAscending(…){ int i, i2; int intMinScore, intMinSubscript, intHoldValue;

for (i = 0; i < cintNumberOfStudents - 1; i++) //-1 so we don’t all the way to the bottom {

intMinSubscript = i; intMinScore = cintTestScores[i]; for (i2 = i + 1; i2 < cintNumberOfStudents; i2++)

{ if {cintTestScore[i2] < intMinScore)

{ intMinSubscript = i2; intMinScore = intTestScores[i2]; } }

intHoldValue = cintTestScores[i]; //swap values cintTestScores[i] = cintTestScores[intMinSubscript]; cintTestScore[intMinSubscript] = intHoldValue; }}

Page 22: CIS162AD - C# Arrays – Part 2 13_arrays_sorting.ppt

CIS162AD 22

Sequential Search Algorithm

Before searching, the data is usually sorted first. Look through the array elements from the first to the

last looking for a match. After a match is found, we are going to do something

with item found later, so the index of where the item was found must be saved.

If the item was not found, we also need to record this using a flag or special value, so that the error can be reported.

Page 23: CIS162AD - C# Arrays – Part 2 13_arrays_sorting.ppt

CIS162AD 23

Search Array – part 1

private void searchArray(…) int i; int intSearchNumber; int intNumberLocation;

bool blnNumberFound; blnNumberFound = false; intSearchNumber = int.Parse(txtSearch.Text);

//see next slide for the rest of the method

Page 24: CIS162AD - C# Arrays – Part 2 13_arrays_sorting.ppt

CIS162AD 24

Search Array – part 2 for (i = 0; i < cintNumberOfStudents; i++) { if (intSearchNumber = = cintTestScores[i])

{ blnNumberFound = true; intNumberLocation = i;

lblOutput.Text = intSearchNumber.ToString(“N0”) + “ is located in array position “ + _

intNumberLocation. ToString(“N0”); } }

if (blnNumberFound = = false) lblOutput.Text = intSearchNumber.ToString(“N0”) +

“ is not in the array.“;}

Page 25: CIS162AD - C# Arrays – Part 2 13_arrays_sorting.ppt

CIS162AD 25

Search Array – Match FoundSubscript Value

[0] 10

[1] 20

[2] 30

[3] 40

[4] 50

[5] 100

[6] 0

… …

[19] 0

intSearchNumber = 40.

For loop walks through array checking if cintTestScores(i) = = intSearchNumber.

When a match is found, the subscript value is displayed (3).

Page 26: CIS162AD - C# Arrays – Part 2 13_arrays_sorting.ppt

CIS162AD 26

Search Array – Early ExitSubscript Value

[0] 10

[1] 20

[2] 30

[3] 40

[4] 50

[5] 100

[6] 0

… …

[19] 0

intSearchNumber = 25.

In the for loop we should also check if intSearchNumber < cintTestScores[i] .

If it is, then we know that we will not find the value. We can exit search.

Must be sorted.

Page 27: CIS162AD - C# Arrays – Part 2 13_arrays_sorting.ppt

CIS162AD 27

Search Array – Early Exit for (i = 0; i < cintNumberOfStudents; i++) { if (intSearchNumber = = cintTestScores[i])

{ blnNumberFound = true; intNumberLocation = i;

lblOutput.Text = intSearchNumber.ToString(“N0”) + “ is located in array position “ + _

intNumberLocation. ToString(“N0”); } else if (intSearchNumber < cintTestScores[i]) {

lblOutput.Text = "Match not found - Early Exit “;

break; // get out for loop } }

Page 28: CIS162AD - C# Arrays – Part 2 13_arrays_sorting.ppt

CIS162AD 28

Parallel Arrays An array is used to process a collection of data all of

which is of the same data type (Integer, Decimal, String, etc.).

When there is related data of different data types, then the data must be loaded into separate but parallel Arrays.

This means that related values are loaded into different arrays but are connected to each by the subscript value.

All of the related values will have the same subscript value.

Page 29: CIS162AD - C# Arrays – Part 2 13_arrays_sorting.ppt

CIS162AD 29

Parallel Arrays – Simplified Example

Names and scores stored in a file

string[ ] cstrName = new string[19]; int[ ] cintScore = new int[19];

for (i = 0; i < 20; i++){

cstrName[i] = studentStreamReader.ReadLine( );cintScore[i] =

int.Parse(studentStreamReader.ReadLine( ));}

The related student data in different arrays must be kept together, especially when sorting.

Page 30: CIS162AD - C# Arrays – Part 2 13_arrays_sorting.ppt

CIS162AD 30

Sorting Parallel Arrays

If sorting by Name, John would be moved to the first position. The data in the related array (Score of 70) must also be swapped. The sort routine would require additional swap statements.

Subscript Name

[0] Todd

[1] Mary

[2] John

[3]

Subscript Score

[0] 90

[1] 50

[2] 70

[3] 0

Page 31: CIS162AD - C# Arrays – Part 2 13_arrays_sorting.ppt

Comparing Strings The only comparison operators defined for a

string are == and !=. To find less than or greater than use CompareTo method.

if (cstrName[i2].CompareTo(strMinName) < 0)

The CompareTo method returns:-1 if current element is less than the compare element 0 if current element is equal to the compare element 1 if currernt element is greater than the compare element

CIS162AD 31

Page 32: CIS162AD - C# Arrays – Part 2 13_arrays_sorting.ppt

CIS162AD 32

Array Class Sort & Search Methods

Along with the Length property and GetUpperBound method, the array class also has a Sort and BinarySearch method.

Array.Sort(arrayName) sorts the elements in a one-dimensional array into ascending order.

Array.Sort will not work with parallel arrays because associated data are stored in different arrays.

Array.BinarySearch(arrayName, searchValue) searches a one-dimensional array that is sorted in ascending order for an element with a specified value. It returns the index of the element if found.

Page 33: CIS162AD - C# Arrays – Part 2 13_arrays_sorting.ppt

CIS162AD 33

Two Dimensional Array

Single Dimensional Arrays are thought of as one column and many rows.

Single Dimensional Arrays require one subscript to reference an individual element.

Two Dimensional Arrays are many columns and many rows.

Two Dimensional Arrays require two subscripts to reference an individual element.

Page 34: CIS162AD - C# Arrays – Part 2 13_arrays_sorting.ppt

CIS162AD 34

Two Dimensional Array - Example Sum sales data for 10 departments and 4 quarters.

decimal[,] decSales = new decimal[10, 4];

for (i = 0; i < 10; i++) // 0 – 9 {

for (j = 0; j < 4; j++) // 0 – 3 {

decTotal += decSales[i, j];}

}

Each individual element requires two subscripts.

Page 35: CIS162AD - C# Arrays – Part 2 13_arrays_sorting.ppt

CIS162AD 35

Two Dimensional Array - Data

Subscript i is going down the rows.

Subscript j is going across the columns.

Subscripts [0] [1] [2] [3]

[0] 10 15 25 30

[1] 20 22 32 42

[2] 30 33 43 15

[3] 0 0 0 0

[etc.] 0 0 0 0

10, 15, 25, 3020, 22, 32, 4230, 33, 43, 15

Page 36: CIS162AD - C# Arrays – Part 2 13_arrays_sorting.ppt

CIS162AD 36

Name Array – 1D Need an array

to store the names of 5 people that are head of the household.

string[ ] strName = new string[5]

Juan Marquez

John Smith

Sue Bradley

Pat West

Mark Jones

Page 37: CIS162AD - C# Arrays – Part 2 13_arrays_sorting.ppt

CIS162AD 37

Name Array – 2D Need an array

to store 5 names, but first and last name separately.

string[ , ] strName

= new string[5,2]

Juan Marquez

John Smith

Sue Bradley

Pat West

Mark Jones

Page 38: CIS162AD - C# Arrays – Part 2 13_arrays_sorting.ppt

CIS162AD 38

Name Array – 3D Need an array to

store the first and last names of up to 5 household members of 4 households.

string[ ,, ] strName = new string[4,5,2]

West is in strName[0,3,1].

household, row, col

Juan Marquez

John Smith

Sue Bradley

Pat West

Mark Jones

Page 39: CIS162AD - C# Arrays – Part 2 13_arrays_sorting.ppt

CIS162AD 39

Name Array – 4D Need an array to store the first and last names of up

to 5 household members of 4 house holds for two different years.

string[ ,,, ] strName = new string[2,4,5,2] See next slide. The first dimension is the cube (year). West is in strName[0,0,3,1] and [1,0,3,1].

Page 40: CIS162AD - C# Arrays – Part 2 13_arrays_sorting.ppt

CIS162AD 40

Name Array – 4D picture

Juan Marquez

John Smith

Sue Bradley

Pat West

Mark Jones

Juan Marquez

John Smith

Sue Bradley

Pat West

Mark Jones

Page 41: CIS162AD - C# Arrays – Part 2 13_arrays_sorting.ppt

CIS162AD 41

Multi-Dimensional Arrays Arrays are actually stored consecutively in memory, not

in a form represented in the drawings in the prior slides. We draw pictures so that we can visually see the data we

are trying to manipulate. The computer can handle as many dimensions as you

would like to add. 3 or 4 dimensions should be our maximum. Keep in mind that eventually you or someone will need

to maintain the program. If the array is to complex, it will take a while to get reacquainted with the logic.

Page 42: CIS162AD - C# Arrays – Part 2 13_arrays_sorting.ppt

CIS162AD 42

Summary Declaring Arrays Loading Arrays Processing Arrays Single Dimensional Multi Dimensional The best way to understand these slides is to work

through the examples using your own values. Desk check the logic to see how values are sorted.