



Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
The implementation of sorted vectors, which are used to maintain a sorted sequence of elements. The use of binary search for maintaining order during insertion and deletion, and the benefits of using a sorted vector for search operations. The document also compares the merge sort and quick sort algorithms for sorting the underlying vector data.
Typology: Exams
1 / 5
This page cannot be seen from the preview
Don't miss anything!




Ant 0 Bird 1 Cat 2 Dog 3 Fox 4 Goat 5 Horse 6 Lion 7 Newt 8 Rat 9 Snake 10
Why use composition ratherthan inheritance?
//} NO NEW METHODS.
int idx = binarySearch(obj);if (idx < data.sizereturn data.elementAt(idx); && data.elementAt(idx).equals(obj)) }elsethrow new^ NoSuchElemenException(String.valueOf(obj));. publicint idx = binarySearch(obj);if (idx < data.size void removeElement(Object && data.elementAt(idx).equals(obj)) obj) { elsereturnthrow new^ data.elementAt(idx); NoSuchElemenException(String.valueOf(obj));. Time complexity:^ }
public void sort(Indexed data) { … }
2 4 6 1 3 5 7
What’s next?^1 2
1 112 11223 2213134 331241245 44353561212 5512346123467
private Comparator test;private Indexedprivate Vector data;buf = new Vector(); public MergeSort() { test = new DefaultComparator(); }public MergeSort(Comparator t) { test = t; } public voiddata =mergeSort(0, v.size()); v; sort(Indexed v) {buf.ensureCapacity(v.size()); }private void mergeSort(int low, int high) { ... } }private void^ merge(int^ low, int mid, int high)^ { ... }
to compare.^ Tell it how Indexed data.Can sort^ any
int ibuf.setSize(0);while = low,(i < mid || j j = mid; < high) { if (^) if (j <(i < mid) { high && test.compare(data.elementAt(j),data.elementAt(i) < 0) }elsebuf.addLast(data.element(j++));^ buf.addLast(data.element(i++)); }else buf.addLast(data.element(j++)); j for (i = = buf.size();data.setElement(buf.elementAt(i), low 0; i < (^) j; i++)// Copy buffer back to original area. + i); }
Pivot
< Pivot Pivot >= Pivot
... public Object findNth(int idx) // All same as before. { if(idx < 0)) || (idxreturn findNth(n,throw NoSuchElementException(); 0, > data.size()))data.size()); }private Object findNth(int n, int low, int high) { int idx = if (idx == pivot(low, n) return high, (high+low)/2);data.elementAt(n); // Partition data.// Done? }^ if (n < idx) return findNth(n, low,^ return^ findNth(n,^ idx^ + 1, high);^ idx);^ // No: try again. }