- 114 Views
- Uploaded on
- Presentation posted in: General

Arrays

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.

- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -

Arrays

Searching & Sorting

Briana B. Morrison

CSE 1302C

Spring 2010

Declaring arrays

Instantiating arrays

Operations on arrays

Searching

Sorting

Hold several values of the same type (homogeneous)

Based on a slot number (the index number)

Instant access

Linear (one after the other)

Static – once their size is set, it’s set…

Things to notice

There are 7 slots, with index numbers 0 – 6

The name of the array is myArray

Easy to be off by one

1

2

3

4

5

6

0

myArray

<data type>[] <name> = new <data type> [<size>];

new brings complex variables to life in C#

Notice that we can create an array of any data type, just by changing the data type!

An array of shorts:

short[] someArray = new short[50];

An array of floats:

float[] myArray = new float[25];

An array of booleans:

bool[] list = new bool[65];

An array of chars:

char[] characters = new char[255];

<data type>[] <name> = new <data type> [<size>] {VALUES};

Or

<data type>[] <name> = {VALUES};

You must specify which slot you are putting information in

Example:

int[] myArray = new int[50];

myArray[3] = 12;

This won’t work:

int[] myArray = new int[50];

myArray = 12;

Data type on the left of = is an array

Data type on right of = is an int

0

1

2

3

4

49

…

12

Copying information out of a particular slot

Example:

int clientAge;

clientAge = myArray[4];

This copies information from the fifth slot (slot four) into the variable clientAge

For most arrays, you will use a loop to initialize

Problem: create an array of 50 bytes and fill each slot with the number 42

Solution:

byte[] myList = new byte[50];

for (int counter=0; counter < 50; counter++) {

myList[counter] = 42;

}

- Sequential
- What if array is sorted
- Binary

- Searching is the process of finding a target element within a group of items called the search pool
- The target may or may not be in the search pool
- We want to perform the search efficiently, minimizing the number of comparisons
- Let's look at two classic searching approaches: linear search and binary search

- A Sequential Search can be used to determine if a specific value (the search key) is in an array.
- Approach is to start with the first element and compare each element to the search key:
- If found, return the index of the element that contains the search key.
- If not found, return -1.
- Because -1 is not a valid index, this is a good return value to indicate that the search key was not found in the array.

public int findWinners( int key )

{

for ( int i = 0; i < winners.length; i++ )

{

if ( winners[i] == key )

return i;

}

return -1;

}

- When the array is sorted, we can implement a more efficient algorithm for a sequential search.
- If the search key is not in the array, we can detect that condition when we find a value that is higher than the search key.
- All elements past that position will be greater than the value of that element, and therefore, greater than the search key.

public intsearchSortedArray( int key )

{

for ( inti = 0; i < array.length

&&array[i] <= key; i++ )

{

if ( array[i] == key )

return i;

}

return –1; // end of array reached without

// finding keyor

// an element larger than

// the key was found

}

- A Binary Search is like the "Guess a Number" game.
- To guess a number between 1 and 100, we start with 50 (halfway between the beginning number and the end number).
- If we learn that the number is greater than 50, we immediately know the number is not 1 - 49.
- If we learn that the number is less than 50, we immediately know the number is not 51 - 100.
- We keep guessing the number that is in the middle of the remaining numbers (eliminating half the remaining numbers) until we find the number.

- The "Guess a Number" approach works because 1 - 100 are a "sorted" set of numbers.
- To use a Binary Search, the array must be sorted.
- Our Binary Search will attempt to find a search key in a sorted array.
- If the search key is found, we return the index of the element with that value.
- If the search key is not found,we return -1.

- We begin by comparing the middle element of the array and the searchkey.
- If they are equal, wefound the searchkey and return the index of the middle element.
- If the middle element's value isgreaterthan the searchkey, then the searchkeycannotbefound in elementswithhigherarray indexes. So, we continue oursearch in the lefthalf of the array.
- If the middle element's value islessthan the searchkey, then the searchkeycannotbefound in elementswithlowerarray indexes. So, we continue oursearch in the right half of the array.

- As we keep searching, the subarray we search keeps shrinking in size. In fact, the size of the subarray we search is cut in half at every iteration.
- If the search key is not in the array, the subarray we search will eventually become empty. At that point, we know that we will not find our search key in the array, and we return –1.

- For example, we will search for the value 7 in this sorted array:
- To begin, we find the index of the center element, which is 8, and we compare our search key (7) with the value 45.

- Because 7 is less than 35, we eliminate all array elements higher than our current middle element and consider elements 0 through 7 the new subarray to search.
- The index of the center element is now 3, so we compare 7 to the value 8.

- Because 7 is less than 8, we eliminate all array elements higher than our current middle element (3) and make elements 0 through 2 the new subarray to search.
- The index of the center element is now 1, so we compare 7 to the value 6.

- Because 7 is greater than 6, we eliminate array elements lower than our current middle element (1) and make element 2 the new subarray to search.
- The value of element 2 matches the search key, so our search is successful and we return the index 2.

- This time, we search for a value not found in the array, 34. Again, we start with the entire array and find the index of the middle element, which is 8.
- We compare our search key (34) with the value 45.

- Because 34 is less than 45, we eliminate array elements higher than our current middle element and consider elements 0 through 7 the new subarray to search.
- The index of the center element is now 3, so we compare 34 to the value 8.

- Because 34 is greater than 8, we eliminate array elements lower than our current middle element and consider elements 4 through 7 the new subarray to search.
- The index of the center element is now 5, so we compare 34 to the value 15.

- Again, we eliminate array elements lower than our current middle element and make elements 6 and 7 the new subarray to search.
- The index of the center element is now 6, so we compare 34 to the value 22.

- Next, we eliminate array elements lower than our current middle element and make element 7 the new subarray to search.
- We compare 34 to the value 36, and attempt to eliminate the higher subarray, which leaves an empty subarray.
- We have determined that 32 is not in the array. We return -1 to indicate an unsuccessful search.

public intbinarySearch( int [] array, int key )

{

int start = 0, end = array.length - 1;

while ( end >= start )

{

int middle = ( start + end ) / 2;

if ( array[middle] == key )

return middle; // key found

else if ( array[middle] > key )

end = middle - 1; // search left

else

start = middle + 1; // search right

}

return -1; // key not found

}

- Sorting is the process of arranging a list of items in a particular order
- The sorting process is based on specific value(s)
- sorting a list of test scores in ascending numeric order
- sorting a list of people alphabetically by last name

- There are many algorithms, which vary in efficiency, for sorting a list of items

- When an array's elements are in random order, our Sequential Searchmethod needs to look at every element in the array before discovering that the search key is not in the array. This is inefficient; the larger the array, the more inefficient a Sequential Searchbecomes.
- We could simplify the search by arranging the elements in numeric order, which is called sorting the array. Once the array is sorted, we can use various search algorithms to speed up a search, including binary search.

- We will review three different sorts:
- Selection Sort
- Bubble Sort
- Insertion Sort

- In a Selection Sort, we select the smallest element in the array and place it at the beginning of the array. Then we select the next-smallest element and put it in the second position in the array, and so on.
- To do this, we consider the unsorted portion of the array as a subarray. Werepeatedly select the smallest value in the currentsubarray and move it to the beginning of the subarray, thenconsider a new subarray by eliminating the elementsthat are in theirsorted locations. We continue until the subarray has only one element. Atthat time, the arrayissorted.

To sort an arraywithnelements in ascendingorder:

1. Consider the nelements as a subarraywithm = nelements.

2. Find the index of the smallest value in thissubarray.

3. Swap the values of the elementwith the smallest value and the element in the first position in the subarray.

4. Consider a new subarray of m = m - 1 elements by eliminating the first element in the previoussubarray

5. Repeatsteps 2 through 4 untilm = 1.

- Algorithm:
for index = 0 to length-2 do

for index2 = index to length -1 do

find minimum value

swap minimum value with list[index]

- To swap two values, we define a temporary variable to hold the value of one of the elements, so that we don't lose that value during the swap.
To swap elements a and b:

- define a temporary variable, temp.
- assign element a to temp.
- assign element b to element a.
- assign temp to element b.

- This code will swap elements 3 and 6 in an int array named array:
int temp; // step 1

temp = array[3]; // step 2

array[3] = array[6]; // step 3

array[6] = temp; // step 4

The picture shows an array of six integers that we want to sort from smallest to largest.

[0][1] [2] [3] [4] [5]

Start by finding the smallest entry.

[0][1] [2] [3] [4] [5]

Start by finding the smallest entry.

Swap the smallest

entry with the

first entry.

[0][1] [2] [3] [4] [5]

- Start by finding the smallest entry.
- Swap the smallest
- entry with the
- first entry.

[0][1] [2] [3] [4] [5]

Part of the array is now sorted.

Sorted side

Unsorted side

[0][1] [2] [3] [4] [5]

Find the smallest element in the unsorted side.

Sorted side

Unsorted side

[0][1] [2] [3] [4] [5]

Find the smallest element in the unsorted side.

Swap with the front of the unsorted side.

Unsorted side

Sorted side

[0][1] [2] [3] [4] [5]

We have increased the size of the sorted side by one element.

Sorted side

Unsorted side

[0][1] [2] [3] [4] [5]

The process continues...

Sorted side

Unsorted side

Smallest

from

unsorted

[0][1] [2] [3] [4] [5]

The process continues

...

Sorted side

Unsorted side

Swap

with

front

[0][1] [2] [3] [4] [5]

The process continues

...

Sorted side

is bigger

Sorted side

Unsorted side

[0][1] [2] [3] [4] [5]

The process keeps adding one more number to the sorted side.

The sorted

side has the smallest numbers, arranged from small to large.

Sorted side

Unsorted side

[0][1] [2] [3] [4] [5]

We can stop

when the

unsorted

side has just

one number,

since that

number

must be the

largest

number.

Sorted side

Unsorted side

[0][1] [2] [3] [4] [5]

The array is now sorted.

We repeatedly selected the smallest element, and moved this element to the front of the

unsorted

side.

[0][1] [2] [3] [4] [5]

- The basic approach to a Bubble Sort is to make multiple passes through the array.
- In each pass, we compare adjacent elements. If any two adjacent elements are out of order, we put them in order by swapping their values.
- At the end of each pass, one more element has "bubbled" up to its correct position.
- We keep making passes through the array until all the elements are in order.

- To sort an array of nelements in ascendingorder, we use a nestedloop:
- The outerloopexecutesn – 1 times.
- For eachiteration of the outerloop, the innerloopstepsthrough all the unsortedelements of the array and does the following:
- Compares the currentelementwith the nextelement in the array.
- If the nextelementissmaller, it swaps the twoelements.

for i = 0 to last array index – 1 by 1

{

for j = 0 to ( last array index – i - 1 ) by 1

{

if ( 2 consecutive elements are not in order )

swap the elements

}

}

- At the beginning, the array is:
- We compare elements 0 (17) and 1 (26) and find they are in the correct order, so we do not swap.

- The inner loop counter is incremented to the next element:
- We compare elements 1 (26) and 2 (5), and find they are not in the correct order, so we swap them.

- The inner loop counter is incremented to the next element:
- We compare elements 2 (26) and 3 (2), and find they are not in the correct order, so we swap them.
- The inner loop completes, which ends our first pass through the array.

- The largest value in the array (26) has bubbled up to its correct position.
- We begin the second pass through the array. We compare elements 0 (17) and 1 (5) and swap them.

- We compare elements 1 (17) and 2 (2) and swap.
- This ends the second pass through the array. The second-largest element (17) has bubbled up to its correct position.

- We begin the last pass through the array.
- We compare element 0 (5) with element 1 (2) and swap them.

- The third-largest value (5) has bubbled up to its correct position.
- Only one element remains, so the array is now sorted.

for ( inti = 0; i < array.length - 1; i++ )

{

for ( int j = 0; j < array.length – i - 1; j++ )

{

if ( array[j] > array[j + 1] )

{

// swap the elements

int temp = array[j + 1];

array[j + 1] = array[j];

array[j] = temp;

}

} // end inner for loop

} // end outer for loop

The Bubblesort algorithm compares adjacent elements and exchanges them if they are out of order.

[0][1] [2] [3] [4] [5]

The first two elements are compared, and are out of order, so they are exchanged.

[0][1] [2] [3] [4] [5]

The first two elements are compared, and are out of order, so they are exchanged.

[0][1] [2] [3] [4] [5]

Now the next two elements are compared. They are in order, so no exchange.

[0][1] [2] [3] [4] [5]

And the process continues...

[0][1] [2] [3] [4] [5]

And the process continues…another exchange.

[0][1] [2] [3] [4] [5]

And the process continues…another exchange.

[0][1] [2] [3] [4] [5]

And the process continues…

Another exchange.

[0][1] [2] [3] [4] [5]

And the process continues… another exchange. The biggest element is now in place.

[0][1] [2] [3] [4] [5]

Now repeat from the first position to

length -1.

[0][1] [2] [3] [4] [5]

Process continues...

[0][1] [2] [3] [4] [5]

Process continues…

[0][1] [2] [3] [4] [5]

Process continues… exchange occurs.

[0][1] [2] [3] [4] [5]

Process continues… exchange occurs.

[0][1] [2] [3] [4] [5]

Process continues… exchange occurs. At this point, the last two elements are in their final sorted order.

[0][1] [2] [3] [4] [5]

Repeat from the beginning location.

[0][1] [2] [3] [4] [5]

Process continues…

[0][1] [2] [3] [4] [5]

Process continues… exchange occurs.

[0][1] [2] [3] [4] [5]

Process continues… exchange occurs.

[0][1] [2] [3] [4] [5]

Process continues… exchange occurs.

[0][1] [2] [3] [4] [5]

Process continues… exchange occurs.

[0][1] [2] [3] [4] [5]

Repeat again from the beginning. Exchange must occur.

[0][1] [2] [3] [4] [5]

Repeat again from the beginning. Exchange must occur.

[0][1] [2] [3] [4] [5]

Process continues...

[0][1] [2] [3] [4] [5]

Process continues… exchange occurs.

[0][1] [2] [3] [4] [5]

Last comparison requires no exchange.

[0][1] [2] [3] [4] [5]

Last comparison requires no exchange.

[0][1] [2] [3] [4] [5]

- The basic approach to Insertion Sort is to make multiple passes through the array.
- In each pass, we “insert” the first element in the unsorted side into its correct sorted position in the sorted side.
- At the end of each pass, all the elements in the “sorted” side are sorted in relation to one another, but may not be in their final sorted position.
- We keep making passes through the array until all the elements are in order.

- Algorithm:
for index = 0 to length-1 do

Item = list[index]

index2 = index -1

placefound = false

while not placefound and index2 >=0

if item < list[index2] then

list[index2 + 1] = list[index2]

index2 = index2 - 1

else

placefound = true

list[index2 +1] = item;

The Insertionsort algorithm also views the array as having a sorted side and an unsorted side.

[0][1] [2] [3] [4] [5]

The sorted

side starts

with just the

first element,

which is not

necessarily

the smallest

element.

Sorted side

Unsorted side

[0][1] [2] [3] [4] [5]

The sorted

side grows

by taking

the front

element

from the

unsorted

side...

Sorted side

Unsorted side

[0][1] [2] [3] [4] [5]

...and

inserting it in

the place

that keeps

the sorted

side

arranged

from small

to large.

Unsorted side

Sorted side

[0][1] [2] [3] [4] [5]

In this example,

the new element

goes in front of the element that was already in the sorted side.

Unsorted side

Sorted side

[0][1] [2] [3] [4] [5]

Sometimes

we are lucky

and the new

inserted item

doesn't need

to move at

all.

Sorted side

Unsorted side

[0][1] [2] [3] [4] [5]

Sometimes we are lucky twice in a row.

Sorted side

Unsorted side

[0][1] [2] [3] [4] [5]

Copy the new element to a separate location.

Sorted side

Unsorted side

[0][1] [2] [3] [4] [5]

Shift elements in the sorted side, creating an open space for the new element.

[0][1] [2] [3] [4] [5]

Shift elements in the sorted side, creating an open space for the new element.

[0][1] [2] [3] [4] [5]

Continue shifting elements...

[0][1] [2] [3] [4] [5]

Continue shifting elements...

[0][1] [2] [3] [4] [5]

...until you reach the location for the new element.

[0][1] [2] [3] [4] [5]

Copy the new element back into the array, at the correct location.

Sorted side

Unsorted side

[0][1] [2] [3] [4] [5]

The last element must also be inserted. Start by copying it...

Sorted side

Unsorted side

[0][1] [2] [3] [4] [5]

How many shifts will occur before we copy this element back into the array? (Value is 15.)

[0][1] [2] [3] [4] [5]

Four items are shifted.

[0][1] [2] [3] [4] [5]

Four items are shifted.

And then the element is copied back into the array.

[0][1] [2] [3] [4] [5]