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

2A BasicArrays

Uploaded by

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

2A BasicArrays

Uploaded by

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

Searching and

Sorting
Algorithms
Unit 2
CPRG304 – Object-Oriented
Programming III
Searching and Sorting
• Donald Knuth:
• “Indeed, I believe that virtually every important
aspect of programming arises somewhere in the
context of sorting or searching!”

• It’s what all our software must do!


• We interact with data to locate a specific item =
searching
• To find something easier, we have to order it in a
specific way = sorting

• How our data is stored affects how we can


search and sort!
Arrays
• A sequence of indexed elements:
low low+1 low+2 high-2 high-1 high array indexes
a
array elements

• The size of the array is fixed when the array is


constructed
• Static-sized, cannot be changed
• Each array element has a fixed and unique index
• The index range from a lower bound to an upper bound
• Any array element can be accessed in O(1) time
• Inspected or updated
Java Arrays
• A Java array consist of elements are either values of a
primitive type or objects of a class
• A Java array of length n has indexes of lower bound 0 and
upper bound n–1

• A Java array is itself an object, allocated dynamically by


new T[n]
class tag length 0 1 n–2 n–1
a
T[] n

array elements
Java Primitive Array
• Example:
int[] primes = new int[5];
primes[0] = 2;

primes[0] =11;
• Example shorthand:
• int[] primes = {2, 3, 5, 7, 11};

class tag length 0 1 2 3 4


primes int[] 5 2 3 5 7 11

• Arrays are an object in Java


• Created during run-time (dynamically allocated)
• Resides in dynamic memory (the Java heap)
• The area of memory used to store objects instantiated by the JVM (run-time)
Java Object Array
• Example:
Date[] holidays = new Date[3];
holidays[0] = new Date(2021, 10, 11);
holidays[1] = new Date(2021, 11, 11);
holidays[2] = new Date(2021, 12, 25);
class tag length 0 1 2
holidays Date[] 3
class tag y m d
Date 2021 12 25
class tag y m d
Date 2021 11 11
class tag y m d
Date 2021 10 11
Concept Checkpoint
• What is wrong in the following code?

1 public class Test {


2 public static void main(String[] args) {
3 java.util.Date[] dates = new java.util.Date[10];
4 System.out.println(dates[0]);
5 System.out.println(dates[0].toString());
6 }
7 }
Subarrays
• A sequence of consecutive elements that forms a part of
a larger array

• Notation: let a[l..r] be the subarray consisting of


elements a[l], …, a[r]
• Subarray
0
notation
1 2
is used
3
here,5 but is
4 6
not
7
supported
8 9
by Java
a

subarray a[1..3] subarray a[6..9]

• Length of subarray a[l..r] is r – l + 1


Copying and Passing Arrays
• Copying Arrays, beware of copies vs. aliases
• list1 = list2 will create an alias for the reference not a
copy of the contents of the array
• Copy contents using loop or the
System.arraycopy(srcArray, srcPos, trgtArray,
trgtPos, length) method

• Passing Arrays
• Arrays are objects thus they are passed by reference
Sorted Arrays
• A (sub)array is sorted if its elements are in ascending order
• i.e., each element is less than or equal to the element on its
right

• The meaning of the comparison “x is less than y” must be


defined for each data type
• Meaning of less for numbers:
• x is numerically less than y, i.e., x < y
• Conventional meaning of less for Strings:
• x precedes y lexicographically (dictionary order) E.g.: “bat” is less than
“bath”, which is less than “bay”
• Conventional meaning of less for Date:
• Today precedes tomorrow (“earlier”)
Comparable vs Comparator
• Java provides 2 interfaces for comparisons:

1. public interface Comparable<T>


• For objects that have a natural order

2. public interface Comparator<T>


• For objects that:
• Can have multiple comparison attributes
• You have no control over
• Needs to implement the Strategy design pattern
Brief Introduction to Generics
• The <T> is like a
placeholder
• Allows it to be replaced by an
actual type later!
• Done by the class
implementing the interface

• Why not use Object?


• Everything is a Object!
• We can’t compare “cat” with 42
• Java can’t enforce types
The Comparable Interface
• If a class implements Comparable, it must implement
compareTo() in accordance with its “contract”

/** @return a negative integer if this object is less than that,


* or zero if this object is equal to that,
* or a positive integer if this object is greater than that. */
public int compareTo(T that);

• The compareTo method captures the notion of less or


greater than for objects
The Comparator Interface
• An external class (or multiple classes) that implements
Comparator can be used

• The compare() method implements the comparison of objects


to impose an order
/** @return a negative integer if the first object is less than
* the second object,
* or zero if the first object is equal to the second object,
* or a positive integer if the first object is greater than the
* second object */
public int compare(T o1, T o2);
Manipulating Arrays
• How do you find an element in an array of n elements?
• Via index: direct access – O(1)
• Via a value of the element: sequential – O(n)
0 1 2 3 4 5 6 7 8 9
a

• Add an element?
• Must shift every element to the right to make room
• O(n)
• Remove an element?
• Must shift every element to the left to fill the gap
• O(n)
Array Insertions
• Given a (sub)array a[left..right], insert a value val at
a[ins]
• If necessary, shift values right to make room for it

• Array insertion algorithm to insert val at index ins in


a[left..right], where left  ins  right):
Copy a[ins..right] into a[ins+1…right+1]
Copy val into a[ins]
Terminate
Array Deletions
• Given a (sub)array a[left..right], delete the value at
a[del]
• If necessary, shift values left to fill the gap

• Array deletion algorithm to delete the value at index


del in a[left..right], where left  del  right):
Copy a[del+1..right] into a[del…right-1]
Make a[right] unoccupied
Terminate
Another Way to Search an Array
• What we’ve assumed so far is linear search
• Works for unsorted and sorted arrays
• Always O(n) for successful or unsuccessful search

• If the array is sorted then we can perform binary search


• Performs much better!
• Invariant: a rule that is always true at every step of the
algorithm
• With binary searches, the invariant is that the array is sorted
• Like an assumption
• The condition that must be true to execute correctly
Binary Search
• To find which (if any) element of the sorted (sub)array
a[left..right] equals target:
Set low = left, and set high = right
While low  high:
Let mid be an integer about midway between low and high
If target equals a[mid], terminate with answer mid
If target is less than a[mid], set high = mid–1
If target is greater than a[mid], set low = mid+1
Terminate with answer none
left low–1 low high high+1 right
a

known to be less than target still to be searched known to be greater than target
Binary Search Analysis
• Counting operations:
• If the search is unsuccessful, these steps are repeated as often
as we must halve n to reach 0:
• Number of comparisons = 3 (floor(log2 n) + 1)
• If the search is successful, these steps are repeated at most that
many times:
• Maximum number of comparisons = 3 floor(log2 n) + 3

• In either case, the time complexity is O(log n)


• Linear search is always O(n)
• Trade-off: the array must always be sorted for binary search!
• What’s the performance impact for keeping the array sorted?
Shape Comparisons in Assignment
• Your project should be able to compare using one of 3
criteria:
1. By height – this is just an attribute of the object (using
comparable)
2. By base area – calculated from one or more attributes of the
object (using comparator)
3. By volume – calculated from one or more attributes of the
object (using comparator)

• Formulas for these calculations are given in the


PolygonFormula.pdf document
Shapes
• Array[Shape] to store all the objects
• 4 types of shapes:

• 4 different prisms:
Shape Classes
Cylinder Cone Pyramid
double height; double height; double height;
double radius; double radius; double side;
double calcVolume(); double calcVolume(); double calcVolume();
double calcBaseArea(); double calcBaseArea(); double calcBaseArea();

SquarePrism TriangularPrism PentagonalPrism OctagonalPrism


double height; double height; double height; double height;
double side; double side; double side; double side;
double calcVolume(); double calcVolume(); double calcVolume(); double calcVolume();
double calcBaseArea(); double calcBaseArea(); double calcBaseArea(); double calcBaseArea();
Data Modelling in OOP
• Make our code reusable, maintainable and scalable!
Prism Shape
double height; double height;
double side; double calcVolume();
double calcVolume(); double calcBaseArea();
double calcBaseArea();

• Now we have a base class to compare the height!


• Shape implements the Comparable interface
public int compareTo(Shape s){
if ( this.getHeight() > s.getHeight() ) return 1;
else if ( this.getHeight() < s.getHeight() ) return -1;
else return 0;
}

You might also like