Presentation is loading. Please wait.

Presentation is loading. Please wait.

Algorithms CSCI 235, Spring 2019 Lecture 11 Elementary Sorts

Similar presentations


Presentation on theme: "Algorithms CSCI 235, Spring 2019 Lecture 11 Elementary Sorts"— Presentation transcript:

1 Algorithms CSCI 235, Spring 2019 Lecture 11 Elementary Sorts

2 Sorting algorithms The problem:
Determine the sorted order of a number of elements by comparing them to one another. Given an array A[1 ... n] of values A comparison predicate, less(v1, v2) that determines v1<v2 Then Modify A so that lesseq(A[i], A[i+1]) for 0 < i < n (lesseq determines whether A[i] <= A[i+1]) Measure the running time of this comparison based sorting by the number of less operations performed.

3 Notes on Sorting A[i ... j] is a contiguous segment of A between indices i and j, inclusive. If i > j then A[i ... j] is empty. The array is usually an array of records with a key field to be sorted. The satellite data in the record is sorted along with the key. Fred Mary Jane Key could be name or number. To test whether v1 = v2 we can use the functions eq(v1, v2) and lesseq(v1, v2). eq(a, b) return not(less(a, b)) and not(less(b,a)) lesseq(a,b) return less(a, b) or eq(a, b)

4 More notes In some contexts it is helpful to assume all the elements in the array are distinct. In some cases we may want to measure the number of assignments to arrays and to temporary variables. We may want to model the temporary space required (i.e. memory used). An algorithm is in place if the amount of temporary space is constant (does not change as n increases). A sorting algorithm is stable if it preserves the relative positions of sorted elements. a b c d e b a c d e Sort by numbers Alphabetical order maintained

5 A few more notes Array based sorting algorithms can be adapted to lists. A function that swaps two elements is useful: swap(A, i, j) temp = A[i] A[i] = A[j] A[j] = temp


Download ppt "Algorithms CSCI 235, Spring 2019 Lecture 11 Elementary Sorts"

Similar presentations


Ads by Google