cmps101-hw1 - else binSearch(element e,...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
D a n n y C h i a C M P S 1 0 1 H o m e w o r k # 1 09/29/2010 1) // selection sort (recursive) int indexOf(int x, Array A) { index = -1 for a = 1 to length(A) { if A[a] == x { index = a break } return index } Array selSort(array A) { if length(A) == 1 then return A else { for a = 1 to (n-1) { m = min(A) j = indexOf(m, A) A[j] = A[1] A[1] = m concatenate (A[1], remainder of A) } } } The loop invariant is the statement that we must go through n-1 iterations to ensure that each value is checked. We only need n-1 iterations because we do not have to compare the last value of the array to itself. Since we have to check every value (except the last one) regardless of whether the values are in order, the best and worst cases are both Θ (n 2 ). 2) // binary search (recursive) int binSearch(element e, Array sortedArray) { let m = floor(length(sortedArray))/2 if e == sortedArray[m] then return m else if e < sortedArray[m] then binSearch(element e, sortedArray[1:m])
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Background image of page 2
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: else binSearch(element e, sortedArray[m:length(sortedArray)]) } In the worst case scenario, we have to keep “dividing and conquering” until we get either one or two elements. As such, the worst case run-time is Θ (log n), with it being a base-2 logarithm. 3a) An inversion is basically a pair in the wrong order; they are: (2, 1), (3, 1), (8, 6), (8, 1) and (6, 1). b) A set in the completely “wrong” (i.e., descending) order (i.e., {n, n-1, n-1,… 1}) would have the most inversions, more specifically, (n*(n–1))/2 inversions. c) Insertion sort looks for elements that are out of order. The fewer inversions an array has, the faster the runtime, which is squarely proportional to the number of inversions. d) int invCount(Array A) { ct = 0 n = length(A) for a = 1 to n { for b = a to (n-1) { if A[a] > A[b] then ct++ } }...
View Full Document

This note was uploaded on 11/16/2010 for the course CMPS 101 taught by Professor Tantalo,p during the Spring '08 term at University of California, Santa Cruz.

Page1 / 2

cmps101-hw1 - else binSearch(element e,...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online