0% found this document useful (0 votes)
24 views45 pages

CS REG - Unit 7 - PART TWO

Uploaded by

zhichen.zheng
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views45 pages

CS REG - Unit 7 - PART TWO

Uploaded by

zhichen.zheng
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 45

UNIT 7 - ARRAYLIST

7.1 - INTRODUCTION TO ARRAYLIST


7.2 - ARRAYLIST METHODS
7.3 - TRAVERSING ARRAYLISTS
7.4 - DEVELOPING ALGORITHMS USING ARRAYLISTS
7.5 - SEARCHING
7.6 - SORTING
7.7 - ETHICAL ISSUES AROUND DATA COLLECTION
Overview
● Computers store vast amounts of data. One of the strengths of computers is their ability to find things
quickly. This ability is called searching. For the AP CSA exam you will need to know both linear
(sequential) search and binary search algorithms.

• Sequential or Linear search typically starts at the first element in an array or ArrayList and looks
through all the items one by one until it either finds the desired value and then it returns the index it
found the value at or if it searches the entire array or list without finding the value it returns -1.

• Binary search can only be used on data that has been sorted or stored in order. It checks the middle
of the data to see if that middle value is less than, equal, or greater than the desired value and then
based on the results of that it narrows the search. It cuts the search space in half each time.
Sequential search
• sequential search: Locates a target value in an array/list by examining each element from
start to finish. If found, return index of first occurrence. Otherwise, return -1.

• How many elements will it need to examine?

• Example: Searching the array below for the value 42:


index 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
value -4 2 7 10 15 20 22 25 30 36 42 50 56 68 85 92 103

i
Search in ArrayList of Double
public int sequentialSearch1(ArrayList<Double> arl, double
target, double delta){
for(int i = 0; i < arl.size(); i++){
if(Math.abs(target – arl.get(i)) < delta)
return i;
}
// target not in array
return -1;
}
Lab: Search in an ArrayList of Books for a String
public class Book{
private String description;
// other instance variables and constructor are skipped

public String getDescription(){


return description;
}
}

In a different class, finish your code:

public int findTheWord(String searchedPhrase,


ArrayList<Book> myBooks) {

}
Lab: Search in an ArrayList of Books for a String
Sequential search: int in Array
Implement sequential search using arrays which returns the index of the target or -1 if it is not
found.
public int sequentialSearch(int[] array, int target){
for(int i = 0; i < array.length; i++){
if(array[i] == target)
return i;
}
// target not in array
return -1;
}
Enhanced for loop for searching
As long as we are only *checking* (not modifying) for existence, a for-each loop will work fine.

public boolean isItInHere(string [] words, String search){


for (string word : words){
if (word.equals (search))
return true;
}
return false;

}
Can we make searching faster?
• We can’t make assumptions about the data we are searching, so we
need to check EVERY index (in order) until we either find the data, or
reach the end of the structure.

• However, if the data were sorted, there will be faster ways.


Binary search
binary search: Locates a target value in a sorted array/list by successively eliminating half of
the array from consideration.

• How many elements will it need to examine?

• Example: Searching the array below for the value 42:

index 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
value -4 2 7 10 15 20 22 25 30 36 42 50 56 68 85 92 103

min mid max


Binary search
Implement binary search using arrays. Assume that the array is sorted.

public int binarySearch(int[] sortedArray, int target){


int min = 0, max = sortedArray.length – 1;
while (min <= max) {
int mid = (min + max) / 2;
if (sortedArray[mid] < target)
min = mid + 1;
else if (sortedArray[mid] > target)
max = mid - 1;
else if (sortedArray[mid] == target)
return mid;
}
return -1;
}
A
C
B
UNIT 7 - ARRAYLIST
7.1 - INTRODUCTION TO ARRAYLIST
7.2 - ARRAYLIST METHODS
7.3 - TRAVERSING ARRAYLISTS
7.4 - DEVELOPING ALGORITHMS USING ARRAYLISTS
7.5 - SEARCHING
7.6 - SORTING
7.7 - ETHICAL ISSUES AROUND DATA COLLECTION
Sorting
Rearranging the values in an array or collection into a specific order (usually into
their "natural ordering").
– one of the fundamental problems in computer science
– can be solved in many ways:
• there are many sorting algorithms
• some are faster/slower than others
• some use more/less memory than others
• some work better with specific kinds of data
• some can utilize multiple computers / processors, ...

– comparison-based sorting : determining order by comparing pairs of elements:


•<, >, compareTo, …
Sorting algorithms
There are many sorting algorithms. Wikipedia lists over 40 sorting algorithms. The
following three sorting algorithm will be on the AP exam.

selection sort: look for the smallest element, swap with first element. Look for the second
smallest, swap with second element, etc…

insertion sort: build an increasingly large sorted front portion of array.

merge sort: recursively divide the array in half and sort it. Merge sort will be discussed in
Unit 10.
Selection sort
selection sort: Orders a list of values by repeatedly putting the smallest or largest
unplaced value into its final position.
The algorithm:
• Look through the list to find the smallest value.
• Swap it so that it is at index 0.

• Look through the list to find the second-smallest value.


• Swap it so that it is at index 1.
...
• Repeat until all values are in their proper places.
Selection sort example
Initial array:

index 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
value 22 18 12 -4 27 30 36 50 7 68 91 56 2 85 42 98 25

After 1st, 2nd, and 3rd passes:


index 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
value -4 18 12 22 27 30 36 50 7 68 91 56 2 85 42 98 25

index 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
value -4 2 12 22 27 30 36 50 7 68 91 56 18 85 42 98 25

index 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
value -4 2 7 22 27 30 36 50 12 68 91 56 18 85 42 98 25
1) For an array of n elements, the array is sorted in n – 1 passes.
2) After the kth pass, the first k elements are in their final sorted positions.
public static void selectionSort(int[] elements){

for (int j = 0; j < elements.length - 1; j++){ // traverse the array


int minIndex = j;

// traverse the unsorted part from minIndex+1 to the end


for (int k = j + 1; k < elements.length; k++){

// exchange index, so the you give the smallest value a


smallest index
if (elements[k] < elements[minIndex])
minIndex = k;
}

// swap only if minIndex changed (found something even smaller)


if (j != minIndex){
int temp = elements[j];
elements[j] = elements[minIndex];
elements[minIndex] = temp;
}
}
Questions on selection sort…
Can an enhanced loop be used?

- No, the Selection Sort algorithm needs to know the index of the items it is
working with.

How does the swap occur?


- A third variable is needed to temporarily hold on to the swapped value from
the array since variables can only hold one thing at a time.
int temp = elements[j];
elements[j] = elements[minIndex];
elements[minIndex] = temp;
假设第0个最小, 执行以下内循环+swap算法

内循环寻找*最小值*

找到了*更小的*,更新minIndex

找到最小值,
把现在位置上的数字和minIndex上的互换

执行完外循环1次,确保了第0个是*最小值*;返回执行第二次外循环 – 假设第1个最小
How many times do we need to swap
- changing the original array?

Swap 1: elements = {5, 8, 7, 6, 9}

Swap 2: elements = {5, 6, 7, 8, 9}


4 times
elements = {5, 10, 2, 1, 12}, (minIndex = 5’s index)
2 < 5 (minIndex = 2’s index)
1 < 2 (minIndex = 1’s index)
Swap 1’: {1, 10, 2, 5, 12}

elements = {1, 10, 2, 5, 12}, (minIndex = 10’s index)


2 < 10 (minIndex = 2’s index)
Swap 2’: 1, 2, 10, 5, 12

elements = {1, 2, 10, 5, 12}, (minIndex = 10’s index)


5 < 10 (minIndex = 5’s index)
Swap 3’: 1, 2, 5, 10, 12
Insertion Sort
insertion sort: Shift each element into a sorted sub-list

The algorithm: To sort a list of n elements.


Loop through indices i from 1 to n – 1:
- For each value at position i, inserted into correct position in the sorted list from index 0 to i – 1.

index 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
value -4 12 18 22 27 30 36 50 7 68 91 56 2 85 42 98 25
sorted sub-array (indexes 0-7)
Insertion Sort Algorithm

64 54 58 87 55 54 58 64 87 55
54 less than 64 55 less than 87
Insert 54 before 64 55 less than 64
55 less than 58
54 64 58 87 55 55 greater than 54
58 less than 64 Insert 55 before 58
58 greater than 54
Insert 58 before 64 54 55 58 64 87

54 58 64 87 55
87 greater than 64
Go to next element
public void insertionSort(ArrayList<Integer> list){
for(int i = 1; i < list.size(); i++){

// REMOVE current, then after Comparison, ADD it back


int current = list.remove(i);

// Comparison: between current(at index) with the one


in front(at index-1)
int index = i - 1;
while(index >= 0 && current < list.get(index))
// get ready to slowly move current ahead
index--;

// now ADD current back


list.add(index+1, current);
}
This implementation uses ArrayLists. This code has appeared
} on MC questions on the AP exam. Understand it!
public static void insertionSort(int[] elements){
for (int j = 1; j < elements.length; j++){

int temp = elements[j];


int possibleIndex = j;

while (possibleIndex > 0 && temp <


elements[possibleIndex - 1]){
elements[possibleIndex] = elements[possibleIndex -
1];
possibleIndex--;
}

elements[possibleIndex] = temp;
}
} This implementation uses arrays. This code has appeared
on MC questions on the AP exam. Understand it!
How many times did we move possibleIndex forward?
4, 12, 4, 7, 19, 6
4, 12, 4, 7, 19, 6
possibleIndex -- : change possibleIndex at 4 to [1], 4 is at the
correct place, end while loop

4, 4, 12, 7, 19, 6
4, 12, 4, 7, 19, 6
possibleIndex -- : change possibleIndex at 4 to [1], 4 is at the
correct place, end while loop

4, 4, 12, 7, 19, 6
possibleIndex -- : change possibleIndex at 7 to [2], 7 is at the
correct place, end while loop

4, 4, 7, 12, 19, 6
4, 12, 4, 7, 19, 6
possibleIndex -- : change possibleIndex at 4 to [1], 4 is at the
correct place, end while loop

4, 4, 12, 7, 19, 6
possibleIndex -- : change possibleIndex at 7 to [2], 7 is at the
correct place, end while loop

4, 4, 7, 12, 19, 6
4, 12, 4, 7, 19, 6
possibleIndex -- : change possibleIndex at 4 to [1], 4 is at the
correct place, end while loop

4, 4, 12, 7, 19, 6
possibleIndex -- : change possibleIndex at 7 to [2], 7 is at the
correct place, end while loop

4, 4, 7, 12, 19, 6
4, 12, 4, 7, 19, 6
possibleIndex -- : change possibleIndex at 4 to [1], 4 is at the
correct place, end while loop

4, 4, 12, 7, 19, 6
possibleIndex -- : change possibleIndex at 7 to [2], 7 is at the
correct place, end while loop

4, 4, 7, 12, 19, 6
possibleIndex -- : change possibleIndex at 6 (4, 4, 7, 12, 6, 19),
possibleIndex -- : change possibleIndex at 6 (4, 4, 7, 6, 12, 19),
possibleIndex -- : change possibleIndex at 6, 6 is at the correct
place (4, 4, 6, 7, 12, 19), end while loop

4, 4, 6, 7, 12, 19
Questions on insertion sort…
• Why use a while loop as the inner loop?
• As soon as the condition is failed a while loop will not execute again, if a
for loop was chosen a much more complex middle section of the for loop
header is required.

• Why is the insertion sort better than selection sort?


• The structure is sorted up to the current value of execution.
Insertion Sort
Some properties of insertion sort:
1) For an array of n elements, the array is sorted after n − 1 passes.
2) After the kth pass, a[0], a[1], ..., a[k] are sorted with respect to each other but not necessarily in
their final sorted positions.
3) The worst case for insertion sort occurs if the array is initially sorted in reverse order, since this
will lead to the maximum possible number of comparisons and moves.
4) The best case for insertion sort occurs if the array is already sorted in increasing order. In this
case, each pass through the array will involve just one comparison, which will indicate that “it” is
in its correct position with respect to the sorted list. Therefore, no elements will need to be
moved.

Note: For selection sort, there is no worst or best case. Finding the smallest at each iteration
requires traversing the array to the end.
The Complexity of An Algorithm

The complexity of an algorithm is the amount of resources (elementary operations or loop


iterations) required for running it. (lower the complexity = faster algorithm)

The complexity f(n) is defined in terms of the input size n. For example, sorting an array
should take more resources for larger arrays.

We can approximate the complexity of simple algorithms by counting the number of


iterations in the algorithm of the worst-case scenario.
Complexity - Example 1

How many times as a function of n does the computation x++ executed?

int x = 0;
for(int i = 0; i < n; i++){
x++;
}

Answer: n(linear function of n)

Example: Sequential/Linear Search has complexity n.


Complexity - Example 2

How many times as a function of n does the computation x++ executed?


int x = 0;
for(int i = 0; i < n; i++){
x++;
}

for(int j = 0; j < n; j++){


x++;
}
Answer: 2n
Example: Sequential Search
Complexity - Example 3

How many times as a function of n does the computation x++ executed?

int x = 0;
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
x++;
}
}
Answer: n^2
Example: Selection and Insertion are both quadratic in complexity.
Complexity of Searching Algorithms
Assume the following algorithms are performed on an array of size n.

Sequential Search: for loop in the algorithm requires approximately n


iterations. This is a linear complexity algorithm.

Binary Search: This is a bit harder. Since each comparison eliminates half of the array, it takes
approximately 𝑙𝑜𝑔! 𝑛 iterations. For example, if an array has length 32, it takes about5 comparisons
since 2" = 32. We will cover this in U10.
Complexity of Sorting Algorithms
Assume the following algorithms are performed on an array of size n.

Selection Sort: nested for loops = approximately 𝑛( iterations


(Quadratic complexity).
Insertion Sort: nested for loops = approximately 𝑛( iterations
(Quadratic complexity).

Note: Searching is much faster than sorting.

You might also like