{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

Sorting_Solutions

# Sorting_Solutions - Sheet1 Page 1 Contains static methods...

This preview shows pages 1–3. Sign up to view the full content.

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

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Sheet1 Page 1 /** Contains static methods for sorting, together with the methods that they use. Included are: min, to find the minimum of b[h..k]. insertValue, to insert a value into its sorted position in b[h..k-1]. linearSearch, to find a value in an array. medianOf3, used in quicksort. partition0, used in quicksort, as done in class. partition, used in quicksort, done a bit more efficiently. copy, to return a copy of b[h..k]. merge, used in mergesort. binarySearch, binary search in an array. selectionSort, to sort an array. selectionSort1, to sort an array. insertionSort, to sort an array. mergesort, to sort an array recursively. quicksort0, the basic quicksort algorithm. quicksort, quicksort changed to fix inefficiencies. Dutch National Flag. toString, to create a String that contains elements of an array. */ public class Sorting { /** Given h < k, return the position of the minimum value of b[h..k]. */ public static int min(int b, int h, int k) { int p= h int i= h // {inv: b[p] is the minimum of b[h..i]}, i.e. // // h-------p------------i---------k // b | b[p] is min of this | ? | // -------------------------------- while (i!= k) { i= i+1 if (b[i] < b[p]) Sheet1 Page 2 {p= i } return p } /** b[h..k-1] is sorted, and b[k] contains a value. Sort b[h..k] */ public static void insertValue(int b, int h, int k) { int v= b[k] int i= k /* inv P: (1) Placing v in b[i] makes b[h..k] a permutation of its initial value (2) b[h..k] with b[i] removed is initial b[h..k-1] (3) v < b[i+1..k] */ while ((i != h) && v < b[i-1]) { b[i]= b[i-1] i= i-1 } b[i]= v } /** = index of x in b ---or b.length if x is not in */ public static int linearSearch(int b, int x) { // invariant: x is not in b[0..i-1] int i for (i= 0 {} return b.length } /** b[h..k] has at least three elements. Let x be the value initially in b[h]. Permute b[h..k] and return integer j satisfying R:<br><br> b[h..j-1] <= b[j] = x <= b[j+1..k] */ public static int partition0(int b, int h, int k) { // // h---------------------------k // pre: b |x| ? | for some x // ----------------------------- // // h-------------j-------------k...
View Full Document

{[ snackBarMessage ]}

### Page1 / 16

Sorting_Solutions - Sheet1 Page 1 Contains static methods...

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

View Full Document
Ask a homework question - tutors are online