2A BasicArrays
2A BasicArrays
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!”
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};
• 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
• 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
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
• 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();