Arraysmithjo/classnotes_2xxxx/power... · 2011. 11. 18. · Array Array: • A reserved set of...

51
Array Objectives To understand the concept of arrays To understand the purpose to which we use arrays. To be able to declare references to arrays. To be able to create one-dimensional and two-dimensional arrays. To be able to initialize one-dimensional and two-dimensional arrays To be able manipulate one-dimensional numeric arrays. To become familiar with arrays of objects including strings. To be able to apply the concept of arrays to searching and sorting.

Transcript of Arraysmithjo/classnotes_2xxxx/power... · 2011. 11. 18. · Array Array: • A reserved set of...

Page 1: Arraysmithjo/classnotes_2xxxx/power... · 2011. 11. 18. · Array Array: • A reserved set of contiguous storage locations to hold a fixed number of homogenous data elements. •

Array

Objectives

• To understand the concept of arrays

• To understand the purpose to which we use arrays.

• To be able to declare references to arrays.

• To be able to create one-dimensional and two-dimensional arrays.

• To be able to initialize one-dimensional and two-dimensional arrays

• To be able manipulate one-dimensional numeric arrays.

• To become familiar with arrays of objects including strings.

• To be able to apply the concept of arrays to searching and sorting.

Page 2: Arraysmithjo/classnotes_2xxxx/power... · 2011. 11. 18. · Array Array: • A reserved set of contiguous storage locations to hold a fixed number of homogenous data elements. •

Array

Introduction

Sometimes we have large sets of data that are needed at anytime in a program.

• If we use a single variable to store each value:

a) Each new data value would over write the previous one

b) At any point in time only one value could be accounted for

c) All the previous values would have been lost.

10 15 23

20 35

70 40

45 50 65

int x;

X = X = X = X = X =

X = X = X = X = X =

Using single variable to store data

Page 3: Arraysmithjo/classnotes_2xxxx/power... · 2011. 11. 18. · Array Array: • A reserved set of contiguous storage locations to hold a fixed number of homogenous data elements. •

Array

Sometimes we have large sets of data that are needed at anytime in a program.

• We could use separate variable to represent each value:

a) Each new data value would be stored in its own variable

b) At any point in time we could accounted for each value

c) None of the previous values would ever be lost.

10 15 23

20 35

70 40

45 50 65

int x1, x2, x3, x4, x5, x6, x7, x8, x9, x10;

x1 = x2 = x3 = x4 = x5 =

x6 = x7 = x8 = x9 = x10 =

Using individual variable store data

Page 4: Arraysmithjo/classnotes_2xxxx/power... · 2011. 11. 18. · Array Array: • A reserved set of contiguous storage locations to hold a fixed number of homogenous data elements. •

Array • Yet a third way would be:

a) Store the data contiguously in memory, and

b) Use one common name to refer to each location where data is stored.

• This method gives rise to the concept of array.

referenveVariable

The array

Page 5: Arraysmithjo/classnotes_2xxxx/power... · 2011. 11. 18. · Array Array: • A reserved set of contiguous storage locations to hold a fixed number of homogenous data elements. •

Array

Array:

• A reserved set of contiguous storage locations to hold a fixed number of

homogenous data elements.

• This means that:

1. All the elements in the array have the same data type

The type of values are – any primitive type or any object

2. The size of the array is fixed at compilation time.

3. The size of the array cannot be changed during run time.

Page 6: Arraysmithjo/classnotes_2xxxx/power... · 2011. 11. 18. · Array Array: • A reserved set of contiguous storage locations to hold a fixed number of homogenous data elements. •

Array

10

15

23

40

70

35

20

45

50

65

int x[] The array

Array x references 10 (4 bytes) contiguously placed memory locations

Page 7: Arraysmithjo/classnotes_2xxxx/power... · 2011. 11. 18. · Array Array: • A reserved set of contiguous storage locations to hold a fixed number of homogenous data elements. •

Declaring One-Dimensional Array Variables

• You must declare the array before you can use it. That is, you must specify:

The name of the variable that will reference the array, and

The type of data that the array is expected to store.

• The format for declaring a one-dimensional array is as follows:

data_type arr[];

or

data_type [] arr;

• Where:

data_type is any valid data type (primitive or reference type)

arr is the name of the array variable. The name follows the convention for name variables

[] is the array symbol. The order of placing the array symbol [] is commutative.

Page 8: Arraysmithjo/classnotes_2xxxx/power... · 2011. 11. 18. · Array Array: • A reserved set of contiguous storage locations to hold a fixed number of homogenous data elements. •

Declaring One-Dimensional Array Variables

• int numbers[];

• String str[];

• byte[] someBytes;

• MotorCar sport[];

• char [] consonants;

• double x[];

• Circle [] c1;

Page 9: Arraysmithjo/classnotes_2xxxx/power... · 2011. 11. 18. · Array Array: • A reserved set of contiguous storage locations to hold a fixed number of homogenous data elements. •

Declaring One-Dimensional Array Variables

1. // Declaration does not imply creating the array

2. class ArrayDeclaration

3. {

4. public static void main(String[] arg)

5. {

6. int numbers[];

7. System.out.println(numbers);

8. }

9. }

-------------------Configuration: j2sdk1.4.1_03 <Default>--------------------

C:\listing8.1\ArrayDeclaration.java:7: variable numbers might not

have been initialized System.out.println(numbers);

^ 1 error

Page 10: Arraysmithjo/classnotes_2xxxx/power... · 2011. 11. 18. · Array Array: • A reserved set of contiguous storage locations to hold a fixed number of homogenous data elements. •

Creating One-Dimensional Array

• The format for creating a one-dimensional array is as follows:

• data_type []arr = new data_type [ numberOfCells ];

Or

• data_type arr [] = new data_type [ numberOfCells ];

• int x[ ] = new int[10];

• String str[ ] = new String[10];

• byte [ ] someBytes = new byte[10];

• Circle [ ] c1 = new Circle [10];

• char consonants[ ] = new char [10];

Page 11: Arraysmithjo/classnotes_2xxxx/power... · 2011. 11. 18. · Array Array: • A reserved set of contiguous storage locations to hold a fixed number of homogenous data elements. •

Accessing The Cells Of The Array

0

1

2

3

4

5

6

7

8

9

indeces

referenceVariable • The cells in a linear (one -

dimensional) array are numbered by

the operating system.

• The numbering scheme begins with

the first cell labeled cell 0, the

second is labeled cell 1, the third is

labeled cell 2, and so on.

• These numbers are referred to as the

array indeces.

Page 12: Arraysmithjo/classnotes_2xxxx/power... · 2011. 11. 18. · Array Array: • A reserved set of contiguous storage locations to hold a fixed number of homogenous data elements. •

Alternate Way to Create Array

• Java provides an alternate way to:

Declare

Construct, and

Explicitly initialize an array.

• The format is as follows:

data_type [] arrayName = {<individual values>};

• When using this construct the individual data must be separated by a comma

Page 13: Arraysmithjo/classnotes_2xxxx/power... · 2011. 11. 18. · Array Array: • A reserved set of contiguous storage locations to hold a fixed number of homogenous data elements. •

Alternate Way to Create Array

• Create an array of the first 10 even integers beginning with the number two.

int evenNumbers[] = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20};

• Create an array of all the vowels.

char [] vowels = {„a‟, „e‟, „i‟, „o‟, „u‟};

• Create an array of the character escape sequence. Character escape sequence must also be placed within single quotation marks.

char escapes[] = {'\n', '\r', '\b', '\t', '\\', '\"', '\''};

• Create an array of menu-items for File, Edit, Insert, and Help.

String[] menu = {“File”, “Edit”, “Insert, “Help”};

Page 14: Arraysmithjo/classnotes_2xxxx/power... · 2011. 11. 18. · Array Array: • A reserved set of contiguous storage locations to hold a fixed number of homogenous data elements. •

Manipulating a Linear Array

• You can assign values directly into the array.

• The general format of the assignment is as follows:

arr[i] = value;

Where:

• arr is the name of the array

• i is the array index, and

• value is the data value being assigned to cell.

• For instance, using the array evenNumbers:

evenNumbers [1] = 10;

• Or read value into array, as in:

evenNumbers [6] = GetData.getInt(“Enter an even integer”);

Page 15: Arraysmithjo/classnotes_2xxxx/power... · 2011. 11. 18. · Array Array: • A reserved set of contiguous storage locations to hold a fixed number of homogenous data elements. •

Length of a Linear Array

Each array has an instance variable called length. It specifies the size of the array.

Givne that arra denotes an one-dimensional array, then the expression:

arr.length

retrieves the size of the array arr. The following piece of code finds the size of the array menu, and prints each value

in the array.

int size = menu.length;

for (int i = 0; i < size; i++)

System.out.println( menu[i] + “\n”);

Page 16: Arraysmithjo/classnotes_2xxxx/power... · 2011. 11. 18. · Array Array: • A reserved set of contiguous storage locations to hold a fixed number of homogenous data elements. •

Convert Integer to Binary

Define a class called BinaryDigits that converts an integer value into its binary

equivalence.

Solution

• The class receives an integer value.

• Define a method that decomposes the number into binary digits.

• Return the binary digits.

Algorithm/rule for converting an integer into binary.

• Divide the original number by 2 and

Record the remainder.

Set the number to the quotient

• Repeat the process until the new number becomes zero.

• When the process stops, rewrite the result starting with the last value first.

Page 17: Arraysmithjo/classnotes_2xxxx/power... · 2011. 11. 18. · Array Array: • A reserved set of contiguous storage locations to hold a fixed number of homogenous data elements. •

Convert Integer to Binary

• Let us use the number 53 to test this algorithm.

53/2 = 26 remainder 1

26/2 = 13 remainder 0

13/2 = 6 remainder 1

6/2 = 3 remainder 0

3/2 = 1 remainder 1

2/2 = 0 remainder 1

• Hence the binary equivalence of 53 is 1 1 0 1 0 1

Page 18: Arraysmithjo/classnotes_2xxxx/power... · 2011. 11. 18. · Array Array: • A reserved set of contiguous storage locations to hold a fixed number of homogenous data elements. •

Convert Integer to Binary

Principal variables are:

• The number

• An array to store the remainder

• An integer value to which to set the size of the array

• An indexing variable for both the loop and the array.

Principal methods are:

• The constructor

• An instance method to implement the above algorithm

• We may code the toString method to return the result

Page 19: Arraysmithjo/classnotes_2xxxx/power... · 2011. 11. 18. · Array Array: • A reserved set of contiguous storage locations to hold a fixed number of homogenous data elements. •

Convert Integer to Binary

1. class BinaryDigits

2. {

3. int binary[], x, theNumber, index;

4. static final int MAX = 32;

5. BinaryDigits(int x)

6. {

7. binary = new int[MAX];

8. this.x = x;

9. index = 0;

10. theNumber = x;

11. }

15. void makeBinaryDigits()

16. {

17. // …

25. }

26. public String toString()

27. {

28. // …….

33. }

34. }

Page 20: Arraysmithjo/classnotes_2xxxx/power... · 2011. 11. 18. · Array Array: • A reserved set of contiguous storage locations to hold a fixed number of homogenous data elements. •

Convert Integer to Binary

15. void makeBinaryDigits()

16. {

17. int remainder;

18. while (x > 0 && index < MAX)

19. {

20. remainder = x % 2;

21. binary[index] = remainder;

22. x = x/ 2;

23. index = index + 1;

24. }

25. }

Page 21: Arraysmithjo/classnotes_2xxxx/power... · 2011. 11. 18. · Array Array: • A reserved set of contiguous storage locations to hold a fixed number of homogenous data elements. •

Convert Integer to Binary

26. public String toString()

27. {

28. String s = "The number " + theNumber + " = ";

29. int index = this.index - 1;

30. for (int i = index; i >= 0; i-- )

31. s = s + binary[i] + " ";

32. return s + " in binary";

33. }

Page 22: Arraysmithjo/classnotes_2xxxx/power... · 2011. 11. 18. · Array Array: • A reserved set of contiguous storage locations to hold a fixed number of homogenous data elements. •

Convert Integer to Binary

1. class TestBinary

2. {

3. public static void main(String[] arg)

4. {

5. BbinaryDigits b = new BinaryDigits(53);

6. b.makeBinaryDigits();

7. System.out.println(b);

8. }

9. }

Page 23: Arraysmithjo/classnotes_2xxxx/power... · 2011. 11. 18. · Array Array: • A reserved set of contiguous storage locations to hold a fixed number of homogenous data elements. •

Common Elementary Algorithms

Some of the basic but frequently used algorithms for manipulating arrays.

These algorithms are so important that:

a) Some programming languages including Java make them a standard

part of their definition.

b) Every scholar studying computer science should understand them from

first principle.

Algorithms:

a) List some or all the elements in an array.

b) List array elements in the reverse order of how they were stored.

c) Find aggregate, mean, and the standard deviation of numeric arrays.

d) Search and sort arrays.

Page 24: Arraysmithjo/classnotes_2xxxx/power... · 2011. 11. 18. · Array Array: • A reserved set of contiguous storage locations to hold a fixed number of homogenous data elements. •

Process Array In Reverse Order

• Sometimes it is necessary to access the elements of an array in the reverse

order in which they were stored.

• This concept requires you to understand the indexing format of an array

firmly.

• That is, given an array arr of size N, the first index value is 0 and the last, N-1.

• The format is:

for (int i = N-1; i >= 0; i-- )

statement;

Page 25: Arraysmithjo/classnotes_2xxxx/power... · 2011. 11. 18. · Array Array: • A reserved set of contiguous storage locations to hold a fixed number of homogenous data elements. •

Processing Parallel Arrays

The following arrays show the average monthly rainfall for a given year:

double rainfall[] = {6.2, 7.2, 9.5, 10.8, 8.1, 7.5, 7.7, 11.3, 12.4, 15.9, 7.9, 12.5};

String[] months = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug",

"Sep", "Oct", "Nov", "Dec“ };

Page 26: Arraysmithjo/classnotes_2xxxx/power... · 2011. 11. 18. · Array Array: • A reserved set of contiguous storage locations to hold a fixed number of homogenous data elements. •

Print Quarterly

• Print array values in reverse order of the rainfall reading for each ending

quarter. • Traversal the array for all of the data values.

• The array index ranges from 0 to rainfall.length - 1 (11) inclusive.

• There are four quarters in the year so divide the index range by three.

• The values must be printed when the indices are: 11, 8, 5, and 2. Hence, the

printing must be done when index % 3 is 2.

1. String Print()

2. {

3. String s = “”;

4. for (int i = rainfall.length-1; i >= 0; i--)

5. if (i%3 == 2)

6. s = s + months[i] + " " + rainfall[i] + "\n");

7. return s;

8. }

Page 27: Arraysmithjo/classnotes_2xxxx/power... · 2011. 11. 18. · Array Array: • A reserved set of contiguous storage locations to hold a fixed number of homogenous data elements. •

Sum Values

• This exercise follows similar pattern to the previous exercise.

• The array must be traversed.

• As each element is encountered it gets added to for the aggregate .

1. double sumArray()

2. {

3. double sum = 0;

4.

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

6. sum = sum + rainfall [i];

7.

8. return sum;

9. }

Page 28: Arraysmithjo/classnotes_2xxxx/power... · 2011. 11. 18. · Array Array: • A reserved set of contiguous storage locations to hold a fixed number of homogenous data elements. •

Finding Average

• Once the aggregate is known the average is found by simply dividing the

aggregate by the number of readings.

1. double average()

2. {

3. return sumArray()/rainfall.length;

4. }

Page 29: Arraysmithjo/classnotes_2xxxx/power... · 2011. 11. 18. · Array Array: • A reserved set of contiguous storage locations to hold a fixed number of homogenous data elements. •

List Elements above average

• This exercise requires:

• Getting the average, and

• Traversing the list comparing the average to each array element.

• When you find an element that is larger than the average, a note is made of it.

1. String aboveAvarage()

2. {

3. String s = "";

4. double avg = average();

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

6. if (rainfall [i] > avg)

7. s = s + months[i] + " " + rainfall[i] + "\n";

8. return s;

9. }

Page 30: Arraysmithjo/classnotes_2xxxx/power... · 2011. 11. 18. · Array Array: • A reserved set of contiguous storage locations to hold a fixed number of homogenous data elements. •

Find Highest Value

Consider the following array

1. What is the highest value in the array?

2. How do we find the highest value?

Look at is this way:

25 4 65 80 10

Page 31: Arraysmithjo/classnotes_2xxxx/power... · 2011. 11. 18. · Array Array: • A reserved set of contiguous storage locations to hold a fixed number of homogenous data elements. •

Find the largest element in an array

Look at it this way:

•The largest values we‟ve seen so far is 25.

•So initially 25 is the largest value.

•The next value will be 4

•Then 65, which makes 65 the largest so far.

•Continues this way to the last element, by which time the largest is found

25 4 65 80 10

Page 32: Arraysmithjo/classnotes_2xxxx/power... · 2011. 11. 18. · Array Array: • A reserved set of contiguous storage locations to hold a fixed number of homogenous data elements. •

Finding Largest Value - Code

1. double findHighestReading()

2. {

3. double highestSoFar = rainfall[0];

4.

5. for(int i = 1; i < length; i ++)

6. if ( rainfall [i] > highestSoFar )

7. highestSoFar = rainfall [i];

8.

9. return highestSoFar;

10. }

Page 33: Arraysmithjo/classnotes_2xxxx/power... · 2011. 11. 18. · Array Array: • A reserved set of contiguous storage locations to hold a fixed number of homogenous data elements. •

Array - Graphing

Using the arrays – months and rainfall.

• For each month print x number of stars from the rainfall array.

• Convert each rainfall value to the nearest integer, and

• Print that many stars.

• That is:

1. for each month

2. {

3. int x = (int) Math.floor(rainfall[i])

4.

5. print x number of stars

6. }

Page 34: Arraysmithjo/classnotes_2xxxx/power... · 2011. 11. 18. · Array Array: • A reserved set of contiguous storage locations to hold a fixed number of homogenous data elements. •

Make Horizontal Bar Graph

1. String makeGraph()

2. {

3. String s = "";

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

5. {

6. s = s + months[i] + " ";

7. int x = (int) Math.floor( rainfall[i] );

8.

9. for(int j = 1; j <=x; j++)

10. s = s + "*";

11. s = s + "\n";

12. }

13. return s;

14. }

Page 35: Arraysmithjo/classnotes_2xxxx/power... · 2011. 11. 18. · Array Array: • A reserved set of contiguous storage locations to hold a fixed number of homogenous data elements. •

Array Assignment vs. Copying Array

Given that arr is a one dimensional array, say:

int arr[] = {2, 4, 6, 8};

2

4

6

8

arr

Page 36: Arraysmithjo/classnotes_2xxxx/power... · 2011. 11. 18. · Array Array: • A reserved set of contiguous storage locations to hold a fixed number of homogenous data elements. •

Assigning References to Arrays.

• Consider the statement

• int x[] = arr;

• The statement has the following effect:

2

4

6

8

arr x

Page 37: Arraysmithjo/classnotes_2xxxx/power... · 2011. 11. 18. · Array Array: • A reserved set of contiguous storage locations to hold a fixed number of homogenous data elements. •

Arrays Assign References

• Consider the following statements:

• x[1] = 28;

• x[2] = 34;

• The effect of the code above is as follows:

2

28

34

8

arr x

Page 38: Arraysmithjo/classnotes_2xxxx/power... · 2011. 11. 18. · Array Array: • A reserved set of contiguous storage locations to hold a fixed number of homogenous data elements. •

Make Copy of Array

// Create an array of equal size, and copy the elements one by one.

1. class CopyArray

2. {

3. int arr[], copy[];

4.

5. CopyArray(int [] x)

6. {

7. arr = x;

8. }

9.

10. void copyArray()

11. {

12. copy = new int[arr.length];

13.

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

15. copy[i] = arr[i];

16. }

17. // …. The rest of the code

18. }

Page 39: Arraysmithjo/classnotes_2xxxx/power... · 2011. 11. 18. · Array Array: • A reserved set of contiguous storage locations to hold a fixed number of homogenous data elements. •

Search - Linear

A search yields three pieces of information:

1. If the item looking for is found

2. The position it is found in the list

3. What item is found in the list

Provide accessor methods to return each value.

class RainfallReading

{

boolean found; // Yes or no if item is found

int index; // Position where item is found if it is in the list

double item; // The item itself.

// ……..

}

Page 40: Arraysmithjo/classnotes_2xxxx/power... · 2011. 11. 18. · Array Array: • A reserved set of contiguous storage locations to hold a fixed number of homogenous data elements. •

Linear Search

1. void search(double key)

2. {

3. int i = 0;

4. while (i < rainfall.length && ! found)

5. if ( key == rainfall[i])

6. {

7. found = true;

8. index = i;

9. item = rainfall[i];

10. }

11. else

12. i++;

13. }

Page 41: Arraysmithjo/classnotes_2xxxx/power... · 2011. 11. 18. · Array Array: • A reserved set of contiguous storage locations to hold a fixed number of homogenous data elements. •

Linear Search

1. boolean inList()

2. {

3. return found;

4. }

1. double getItem()

2. {

3. return item;

4. }

1. int getIndex()

2. {

3. return index;

4. }

Page 42: Arraysmithjo/classnotes_2xxxx/power... · 2011. 11. 18. · Array Array: • A reserved set of contiguous storage locations to hold a fixed number of homogenous data elements. •

Selection Sort

• Sort - to arrange a list in either ascending or descending order.

• There are many sorting algorithms

Insertion sort,

Bubble sort, and

Selection sort …… to name a few.

• The sorting algorithm discussed here is the selection sort.

The algorithm requires two steps:

1. Find the location of the smallest element in the unsorted portion of

the list.

2. Exchange/swap the element at the position with the first element in

the unsorted portion of the list.

Page 43: Arraysmithjo/classnotes_2xxxx/power... · 2011. 11. 18. · Array Array: • A reserved set of contiguous storage locations to hold a fixed number of homogenous data elements. •

Selection Sort

[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]

5 30 24 7 25 62 45 16 65 50

[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]

16 30 24 7 25 62 45 5 65 50

Initially the unsorted portion of the list is the entire list.

• Find the position of the smallest element in the list,

• The smallest element is at position 7

• Exchange it with the value at position 0.

Page 44: Arraysmithjo/classnotes_2xxxx/power... · 2011. 11. 18. · Array Array: • A reserved set of contiguous storage locations to hold a fixed number of homogenous data elements. •

Selection Sort

[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]

5 30 24 7 25 62 45 16 65 50

• The unsorted portion of the list begins at index 1

• Find the position of the smallest element in this portion of the list

• The smallest element is at position 3

• Exchange it with the value at position 1.

[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]

5 7 24 30 25 62 45 16 65 50

Page 45: Arraysmithjo/classnotes_2xxxx/power... · 2011. 11. 18. · Array Array: • A reserved set of contiguous storage locations to hold a fixed number of homogenous data elements. •

Selection Sort

[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]

5 7 24 30 25 62 45 16 65 50

• The unsorted portion of the list begins at index 2

• Find the position of the smallest element in this portion of the list,

• The smallest element is at position 7

• Exchange it with the value at position 2.

[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]

5 7 16 30 25 62 45 24 65 50

Page 46: Arraysmithjo/classnotes_2xxxx/power... · 2011. 11. 18. · Array Array: • A reserved set of contiguous storage locations to hold a fixed number of homogenous data elements. •

Selection Sort

[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]

5 7 16 30 25 62 45 24 65 50

• The unsorted portion of the list begins at index 3

• Find the position of the smallest element in this portion of the list,

• The smallest element is at position 7

• Exchange it with the value at position 3.

[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]

5 7 16 24 25 62 45 30 65 50

Page 47: Arraysmithjo/classnotes_2xxxx/power... · 2011. 11. 18. · Array Array: • A reserved set of contiguous storage locations to hold a fixed number of homogenous data elements. •

Selection Sort

[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]

5 7 16 24 25 62 45 30 65 50

• The unsorted portion of the list begins at index 4

• Find the position of the smallest element in this portion of the list,

• The smallest element is at position 4

• Exchange it with the value at position 4.

[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]

5 7 16 24 25 62 45 30 65 50

The pattern continues until the entire list is sorted.

Page 48: Arraysmithjo/classnotes_2xxxx/power... · 2011. 11. 18. · Array Array: • A reserved set of contiguous storage locations to hold a fixed number of homogenous data elements. •

Selection Sort

Applying this to the RainfallReading class. Here is a skeletal outline of the algorithm.

for (int startScan = 0; startScan < rainfall.length – 1; startScan ++)

{

int position = findPosition(startScan );

swap( position, startScan );

}

Note the variable startScan represents the unsorted portion of the list

int findPosition(int startScan )

{

// define method

}

void swap( int i, int j )

{

// define method

}

Page 49: Arraysmithjo/classnotes_2xxxx/power... · 2011. 11. 18. · Array Array: • A reserved set of contiguous storage locations to hold a fixed number of homogenous data elements. •

Selection Sort

1. void selectionSort()

2. {

3. for (int startScan = 0; startScan < rainfall.length - 1; startScan++ )

4. {

5. int position = findPosition(startScan);

6. swap(position, startScan);

7. }

8. }

Page 50: Arraysmithjo/classnotes_2xxxx/power... · 2011. 11. 18. · Array Array: • A reserved set of contiguous storage locations to hold a fixed number of homogenous data elements. •

Selection Sort

1.

2. int findPosition(int startScanFrom)

3. {

4. int position = startScanFrom;

5.

6. // The unsorted portion of the list

7.

8. for (int i = startScanFrom + 1; i < rainfall.length; i++)

9. if (rainfall[i] < rainfall[position])

10. position = i;

11.

12. return position;

13. }

Page 51: Arraysmithjo/classnotes_2xxxx/power... · 2011. 11. 18. · Array Array: • A reserved set of contiguous storage locations to hold a fixed number of homogenous data elements. •

Selection Sort

1. void swap(int i, int j)

2. {

3. // Swap the rainfalls

4. double temp = rainfall[i];

5. rainfall[i] = rainfall[j];

6. rainfall[j] = temp;

7.

8. // Swap the months

9. String str = months[i];

10. months[i] = months[j];

11. months[j] = str;

12. }