

Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!


A. In the worst case, A[] is sorted in increasing order. Outer loop: n times; Inner loop: check “A[j] < A[j-1]” once, twice, n-1 times…. 1+2+…. + (n-1) = O(n^2 ) B. In the best case, A[] is sorted in decreasing order. Outer loop: n times; Inner loop: A[j]>=A[j-1], so only check “A[j] < A[j-1]” for once and then jump out of loop. 1+1+…. + 1 = O(n) A & B sort array elements in increasing order (a bubble sort variation)
C. Runtime is dominated by allocating and copying operation. i.e. how many times “new int[A.length - 1]” and how many times “B[i-1]=A[i]” get executed. 1 st^ time, allocate (n-1) space & copy (n-1) elements; 2 nd^ time, allocate (n-2) spaces & copy (n-2) elements; 2(n-1)+2(n-2)+….+2*1 = O(n^2 ) D. Recurse once Shrink the array range by 1, until we get to 1. So we will recurse n-1 times. C & D find the maximum element in an array
String StringBuffer Property Immutable^ Modifiable Concatenation String str = “abc”; str += “xyz”;
StringBuffer strbuf= “abc”; strbuf.append(“xyz”); Conversion (StringBuffer) str; strbuf.toString();
Please make sure to understand the sorting algorithms pretty well. The following materials may help you refresh selection sort and insertion sort (the provided code is NOT the solution to Problem6).
Intuition: “Remove” the items one at a time from the original array and “Insert” them into a new array, putting them into the correct sorted order as you insert.
Implementation: We could accomplish this by using two arrays as implied above, but that would double our memory requirements. We'd rather be able to sort in place. To actually implement we are going to think of the array or in two parts (sorted & unsorted).
Code: public static <T extends Comparable<? super T>> void insertionSort(T[] a) { for (int i=1; i < a.length; i++) { /* Insert a[i] into the sorted sublist */ T value = a[i]; for (int j = i - 1; j >= 0; j--) { if (a[j].compareTo(value) <= 0) break; a[j + 1] = a[j]; } a[j + 1] = value; } }
Analysis:
Variation: Can we use insertionSort on a linked list? – Sure, in fact it is probably more natural with a linked list. At each iteration simply remove the front node from the list, and “insert it in order” into a second, new list.