21Elementarysorts-2X2.Pdf

Total Page:16

File Type:pdf, Size:1020Kb

21Elementarysorts-2X2.Pdf Algorithms ROBERT SEDGEWICK | KEVIN WAYNE 2.1 ELEMENTARY SORTS 2.1 ELEMENTARY SORTS ‣ rules of the game ‣ rules of the game ‣ selection sort ‣ selection sort Algorithms ‣ insertion sort Algorithms ‣ insertion sort FOURTH EDITION ‣ shellsort ‣ shellsort ‣ shuffling ‣ shuffling ROBERT SEDGEWICK | KEVIN WAYNE ROBERT SEDGEWICK | KEVIN WAYNE http://algs4.cs.princeton.edu ‣ convex hull http://algs4.cs.princeton.edu ‣ convex hull Sorting problem Sample sort client 1 Ex. Student records in a university. Goal. Sort any type of data. Chen 3 A 991-878-4944 308 Blair Ex 1. Sort random real numbers in ascending order. Rohde 2 A 232-343-5555 343 Forbes seems artificial, but stay tuned for an application Gazsi 4 B 766-093-9873 101 Brown item Furia 1 A 766-093-9873 101 Brown Kanaga 3 B 898-122-9643 22 Brown public class Experiment % java Experiment 10 Andrews 3 A 664-480-0023 097 Little { 0.08614716385210452 0.09054270895414829 key Battle 4 C 874-088-1212 121 Whitman public static void main(String[] args) { 0.10708746304898642 int N = Integer.parseInt(args[0]); 0.21166190071646818 Double[] a = new Double[N]; 0.363292849257276 Sort. Rearrange array of N items into ascending order. for (int i = 0; i < N; i++) 0.460954145685913 a[i] = StdRandom.uniform(); 0.5340026311350087 Andrews 3 A 664-480-0023 097 Little Insertion.sort(a); 0.7216129793703496 Battle 4 C 874-088-1212 121 Whitman for (int i = 0; i < N; i++) 0.9003500354411443 Chen 3 A 991-878-4944 308 Blair StdOut.println(a[i]); 0.9293994908845686 Furia 1 A 766-093-9873 101 Brown } Gazsi 4 B 766-093-9873 101 Brown } Kanaga 3 B 898-122-9643 22 Brown Rohde 2 A 232-343-5555 343 Forbes 3 4 Sample sort client 2 Sample sort client 3 Goal. Sort any type of data. Goal. Sort any type of data. Ex 2. Sort strings from file in alphabetical order. Ex 3. Sort the files in a given directory by filename. public class StringSorter { import java.io.File; % java FileSorter . public static void main(String[] args) public class FileSorter Insertion.class { { Insertion.java String[] a = In.readStrings(args[0]); public static void main(String[] args) InsertionX.class Insertion.sort(a); { InsertionX.java for (int i = 0; i < a.length; i++) File directory = new File(args[0]); Selection.class StdOut.println(a[i]); File[] files = directory.listFiles(); Selection.java } Insertion.sort(files); Shell.class } for (int i = 0; i < files.length; i++) Shell.java % more words3.txt StdOut.println(files[i].getName()); ShellX.class bed bug dad yet zoo ... all bad yes } ShellX.java } % java StringSorter words3.txt all bad bed bug dad ... yes yet zoo 5 6 Callbacks Callbacks: roadmap Goal. Sort any type of data. client object implementation import java.io.File; public class File public class FileSorter implements Comparable<File> { { sort() Double String Q. How can know how to compare data of type , , and public static void main(String[] args) ... java.io.File without any information about the type of an item's key? { public int compareTo(File b) File directory = new File(args[0]); { File[] files = directory.listFiles(); ... Insertion.sort(files); return -1; Callback = reference to executable code. for (int i = 0; i < files.length; i++) ... StdOut.println(files[i].getName()); return +1; ・Client passes array of objects to sort() function. } ... The sort() function calls back object's compareTo() method as needed. } return 0; ・ } } Implementing callbacks. ・Java: interfaces. Comparable interface (built in to Java) sort implementation public static void sort(Comparable[] a) C: function pointers. public interface Comparable<Item> ・ { { int N = a.length; ・C++: class-type functors. public int compareTo(Item that); for (int i = 0; i < N; i++) } ・C#: delegates. for (int j = i; j > 0; j--) if (a[j].compareTo(a[j-1]) < 0) ・Python, Perl, ML, Javascript: first-class functions. exch(a, j, j-1); key point: no dependence else break; on File data type } 7 8 Total order Comparable API A total order is a binary relation ≤ that satisfies: Implement compareTo() so that v.compareTo(w) ・Antisymmetry: if v ≤ w and w ≤ v, then v = w. ・Is a total order. ・Transitivity: if v ≤ w and w ≤ x, then v ≤ x. ・Returns a negative integer, zero, or positive integer ・Totality: either v ≤ w or w ≤ v or both. if v is less than, equal to, or greater than w, respectively. ・Throws an exception if incompatible types (or either is null). Ex. ・Standard order for natural and real numbers. ・Chronological order for dates or times. v w v w ・Alphabetical order for strings. w v … ・ less than (return -1) equal to (return 0) greater than (return +1) violates totality: (Double.NaN <= Double.NaN) is false an intransitive relation Built-in comparable types. Integer, Double, String, Date, File, ... Surprising but true. The <= operator for double is not a total order. (!) User-defined comparable types. Implement the Comparable interface. 9 10 Implementing the Comparable interface Two useful sorting abstractions Date data type. Simplified version of java.util.Date. Helper functions. Refer to data through compares and exchanges. public class Date implements Comparable<Date> Less. Is item v less than w ? { private final int month, day, year; private static boolean less(Comparable v, Comparable w) public Date(int m, int d, int y) only compare dates { return v.compareTo(w) < 0; } { to other dates month = m; day = d; year = y; } Exchange. Swap item in array a[] at index i with the one at index j. public int compareTo(Date that) { if (this.year < that.year ) return -1; private static void exch(Comparable[] a, int i, int j) if (this.year > that.year ) return +1; if (this.month < that.month) return -1; { if (this.month > that.month) return +1; Comparable swap = a[i]; if (this.day < that.day ) return -1; a[i] = a[j]; if (this.day > that.day ) return +1; a[j] = swap; return 0; } } } 11 12 Testing Goal. Test if an array is sorted. private static boolean isSorted(Comparable[] a) { for (int i = 1; i < a.length; i++) if (less(a[i], a[i-1])) return false; 2.1 ELEMENTARY SORTS return true; } ‣ rules of the game ‣ selection sort Algorithms ‣ insertion sort ‣ shellsort ‣ shuffling ROBERT SEDGEWICK | KEVIN WAYNE Q. If the sorting algorithm passes the test, did it correctly sort the array? http://algs4.cs.princeton.edu ‣ convex hull A. 13 Selection sort demo Selection sort ・In iteration i, find index min of smallest remaining entry. Algorithm. ↑ scans from left to right. ・Swap a[i] and a[min]. Invariants. ・Entries the left of ↑ (including ↑) fixed and in ascending order. ・No entry to right of ↑ is smaller than any entry to the left of ↑. initial in final order ↑ 15 16 Selection sort inner loop Selection sort: Java implementation To maintain algorithm invariants: public class Selection { ・Move the pointer to the right. public static void sort(Comparable[] a) { int N = a.length; i++; for (int i = 0; i < N; i++) in final order ↑ { int min = i; ・Identify index of minimum entry on right. for (int j = i+1; j < N; j++) if (less(a[j], a[min])) min = j; int min = i; exch(a, i, min); for (int j = i+1; j < N; j++) } if (less(a[j], a[min])) } in final order ↑ ↑ min = j; private static boolean less(Comparable v, Comparable w) { /* as before */ } ・Exchange into position. private static void exch(Comparable[] a, int i, int j) { /* as before */ } } exch(a, i, min); in final order ↑ ↑ 17 18 Selection sort: mathematical analysis Selection sort: animations 2 20 random items Proposition. Selection sort uses (N – 1) + (N – 2) + ... + 1 + 0 ~ N / 2 compares and N exchanges. a[] entries in black i min 0 1 2 3 4 5 6 7 8 9 10 are examined to find the minimum S O R T E X A M P L E 0 6 S O R T E X A M P L E entries in red 1 4 A O R T E X S M P L E are a[min] 2 10 A E R T O X S M P L E 3 9 A E E T O X S M P L R 4 7 A E E L O X S M P T R 5 7 A E E L M X S O P T R 6 8 A E E L M O S X P T R 7 10 A E E L M O P X S T R 8 8 A E E L M O P R S T X entries in gray are 9 9 A E E L M O P R S T X in final position 10 10 A E E L M O P R S T X A E E L M O P R S T X algorithm position Trace of selection sort (array contents just after each exchange) in final order not in final order Running time insensitive to input. Quadratic time, even if input is sorted. http://www.sorting-algorithms.com/selection-sort Data movement is minimal. Linear number of exchanges. 19 20 Selection sort: animations 20 partially-sorted items 2.1 ELEMENTARY SORTS ‣ rules of the game ‣ selection sort Algorithms ‣ insertion sort ‣ shellsort ‣ shuffling algorithm position ROBERT SEDGEWICK | KEVIN WAYNE in final order http://algs4.cs.princeton.edu ‣ convex hull not in final order http://www.sorting-algorithms.com/selection-sort 21 Insertion sort demo Insertion sort ・In iteration i, swap a[i] with each larger entry to its left. Algorithm. ↑ scans from left to right. Invariants. ・Entries to the left of ↑ (including ↑) are in ascending order. ・Entries to the right of ↑ have not yet been seen.
Recommended publications
  • Sort Algorithms 15-110 - Friday 2/28 Learning Objectives
    Sort Algorithms 15-110 - Friday 2/28 Learning Objectives • Recognize how different sorting algorithms implement the same process with different algorithms • Recognize the general algorithm and trace code for three algorithms: selection sort, insertion sort, and merge sort • Compute the Big-O runtimes of selection sort, insertion sort, and merge sort 2 Search Algorithms Benefit from Sorting We use search algorithms a lot in computer science. Just think of how many times a day you use Google, or search for a file on your computer. We've determined that search algorithms work better when the items they search over are sorted. Can we write an algorithm to sort items efficiently? Note: Python already has built-in sorting functions (sorted(lst) is non-destructive, lst.sort() is destructive). This lecture is about a few different algorithmic approaches for sorting. 3 Many Ways of Sorting There are a ton of algorithms that we can use to sort a list. We'll use https://visualgo.net/bn/sorting to visualize some of these algorithms. Today, we'll specifically discuss three different sorting algorithms: selection sort, insertion sort, and merge sort. All three do the same action (sorting), but use different algorithms to accomplish it. 4 Selection Sort 5 Selection Sort Sorts From Smallest to Largest The core idea of selection sort is that you sort from smallest to largest. 1. Start with none of the list sorted 2. Repeat the following steps until the whole list is sorted: a) Search the unsorted part of the list to find the smallest element b) Swap the found element with the first unsorted element c) Increment the size of the 'sorted' part of the list by one Note: for selection sort, swapping the element currently in the front position with the smallest element is faster than sliding all of the numbers down in the list.
    [Show full text]
  • Quick Sort Algorithm Song Qin Dept
    Quick Sort Algorithm Song Qin Dept. of Computer Sciences Florida Institute of Technology Melbourne, FL 32901 ABSTRACT each iteration. Repeat this on the rest of the unsorted region Given an array with n elements, we want to rearrange them in without the first element. ascending order. In this paper, we introduce Quick Sort, a Bubble sort works as follows: keep passing through the list, divide-and-conquer algorithm to sort an N element array. We exchanging adjacent element, if the list is out of order; when no evaluate the O(NlogN) time complexity in best case and O(N2) exchanges are required on some pass, the list is sorted. in worst case theoretically. We also introduce a way to approach the best case. Merge sort [4]has a O(NlogN) time complexity. It divides the 1. INTRODUCTION array into two subarrays each with N/2 items. Conquer each Search engine relies on sorting algorithm very much. When you subarray by sorting it. Unless the array is sufficiently small(one search some key word online, the feedback information is element left), use recursion to do this. Combine the solutions to brought to you sorted by the importance of the web page. the subarrays by merging them into single sorted array. 2 Bubble, Selection and Insertion Sort, they all have an O(N2) In Bubble sort, Selection sort and Insertion sort, the O(N ) time time complexity that limits its usefulness to small number of complexity limits the performance when N gets very big. element no more than a few thousand data points.
    [Show full text]
  • Secure Multi-Party Sorting and Applications
    Secure Multi-Party Sorting and Applications Kristján Valur Jónsson1, Gunnar Kreitz2, and Misbah Uddin2 1 Reykjavik University 2 KTH—Royal Institute of Technology Abstract. Sorting is among the most fundamental and well-studied problems within computer science and a core step of many algorithms. In this article, we consider the problem of constructing a secure multi-party computing (MPC) protocol for sorting, building on previous results in the field of sorting networks. Apart from the immediate uses for sorting, our protocol can be used as a building-block in more complex algorithms. We present a weighted set intersection algorithm, where each party inputs a set of weighted ele- ments and the output consists of the input elements with their weights summed. As a practical example, we apply our protocols in a network security setting for aggregation of security incident reports from multi- ple reporters, specifically to detect stealthy port scans in a distributed but privacy preserving manner. Both sorting and weighted set inter- section use O`n log2 n´ comparisons in O`log2 n´ rounds with practical constants. Our protocols can be built upon any secret sharing scheme supporting multiplication and addition. We have implemented and evaluated the performance of sorting on the Sharemind secure multi-party computa- tion platform, demonstrating the real-world performance of our proposed protocols. Keywords. Secure multi-party computation; Sorting; Aggregation; Co- operative anomaly detection 1 Introduction Intrusion Detection Systems (IDS) [16] are commonly used to detect anoma- lous and possibly malicious network traffic. Incidence reports and alerts from such systems are generally kept private, although much could be gained by co- operative sharing [30].
    [Show full text]
  • Sorting Algorithms Correcness, Complexity and Other Properties
    Sorting Algorithms Correcness, Complexity and other Properties Joshua Knowles School of Computer Science The University of Manchester COMP26912 - Week 9 LF17, April 1 2011 The Importance of Sorting Important because • Fundamental to organizing data • Principles of good algorithm design (correctness and efficiency) can be appreciated in the methods developed for this simple (to state) task. Sorting Algorithms 2 LF17, April 1 2011 Every algorithms book has a large section on Sorting... Sorting Algorithms 3 LF17, April 1 2011 ...On the Other Hand • Progress in computer speed and memory has reduced the practical importance of (further developments in) sorting • quicksort() is often an adequate answer in many applications However, you still need to know your way (a little) around the the key sorting algorithms Sorting Algorithms 4 LF17, April 1 2011 Overview What you should learn about sorting (what is examinable) • Definition of sorting. Correctness of sorting algorithms • How the following work: Bubble sort, Insertion sort, Selection sort, Quicksort, Merge sort, Heap sort, Bucket sort, Radix sort • Main properties of those algorithms • How to reason about complexity — worst case and special cases Covered in: the course book; labs; this lecture; wikipedia; wider reading Sorting Algorithms 5 LF17, April 1 2011 Relevant Pages of the Course Book Selection sort: 97 (very short description only) Insertion sort: 98 (very short) Merge sort: 219–224 (pages on multi-way merge not needed) Heap sort: 100–106 and 107–111 Quicksort: 234–238 Bucket sort: 241–242 Radix sort: 242–243 Lower bound on sorting 239–240 Practical issues, 244 Some of the exercise on pp.
    [Show full text]
  • Improving the Performance of Bubble Sort Using a Modified Diminishing Increment Sorting
    Scientific Research and Essay Vol. 4 (8), pp. 740-744, August, 2009 Available online at http://www.academicjournals.org/SRE ISSN 1992-2248 © 2009 Academic Journals Full Length Research Paper Improving the performance of bubble sort using a modified diminishing increment sorting Oyelami Olufemi Moses Department of Computer and Information Sciences, Covenant University, P. M. B. 1023, Ota, Ogun State, Nigeria. E- mail: [email protected] or [email protected]. Tel.: +234-8055344658. Accepted 17 February, 2009 Sorting involves rearranging information into either ascending or descending order. There are many sorting algorithms, among which is Bubble Sort. Bubble Sort is not known to be a very good sorting algorithm because it is beset with redundant comparisons. However, efforts have been made to improve the performance of the algorithm. With Bidirectional Bubble Sort, the average number of comparisons is slightly reduced and Batcher’s Sort similar to Shellsort also performs significantly better than Bidirectional Bubble Sort by carrying out comparisons in a novel way so that no propagation of exchanges is necessary. Bitonic Sort was also presented by Batcher and the strong point of this sorting procedure is that it is very suitable for a hard-wired implementation using a sorting network. This paper presents a meta algorithm called Oyelami’s Sort that combines the technique of Bidirectional Bubble Sort with a modified diminishing increment sorting. The results from the implementation of the algorithm compared with Batcher’s Odd-Even Sort and Batcher’s Bitonic Sort showed that the algorithm performed better than the two in the worst case scenario. The implication is that the algorithm is faster.
    [Show full text]
  • Data Structures & Algorithms
    DATA STRUCTURES & ALGORITHMS Tutorial 6 Questions SORTING ALGORITHMS Required Questions Question 1. Many operations can be performed faster on sorted than on unsorted data. For which of the following operations is this the case? a. checking whether one word is an anagram of another word, e.g., plum and lump b. findin the minimum value. c. computing an average of values d. finding the middle value (the median) e. finding the value that appears most frequently in the data Question 2. In which case, the following sorting algorithm is fastest/slowest and what is the complexity in that case? Explain. a. insertion sort b. selection sort c. bubble sort d. quick sort Question 3. Consider the sequence of integers S = {5, 8, 2, 4, 3, 6, 1, 7} For each of the following sorting algorithms, indicate the sequence S after executing each step of the algorithm as it sorts this sequence: a. insertion sort b. selection sort c. heap sort d. bubble sort e. merge sort Question 4. Consider the sequence of integers 1 T = {1, 9, 2, 6, 4, 8, 0, 7} Indicate the sequence T after executing each step of the Cocktail sort algorithm (see Appendix) as it sorts this sequence. Advanced Questions Question 5. A variant of the bubble sorting algorithm is the so-called odd-even transposition sort . Like bubble sort, this algorithm a total of n-1 passes through the array. Each pass consists of two phases: The first phase compares array[i] with array[i+1] and swaps them if necessary for all the odd values of of i.
    [Show full text]
  • 13 Basic Sorting Algorithms
    Concise Notes on Data Structures and Algorithms Basic Sorting Algorithms 13 Basic Sorting Algorithms 13.1 Introduction Sorting is one of the most fundamental and important data processing tasks. Sorting algorithm: An algorithm that rearranges records in lists so that they follow some well-defined ordering relation on values of keys in each record. An internal sorting algorithm works on lists in main memory, while an external sorting algorithm works on lists stored in files. Some sorting algorithms work much better as internal sorts than external sorts, but some work well in both contexts. A sorting algorithm is stable if it preserves the original order of records with equal keys. Many sorting algorithms have been invented; in this chapter we will consider the simplest sorting algorithms. In our discussion in this chapter, all measures of input size are the length of the sorted lists (arrays in the sample code), and the basic operation counted is comparison of list elements (also called keys). 13.2 Bubble Sort One of the oldest sorting algorithms is bubble sort. The idea behind it is to make repeated passes through the list from beginning to end, comparing adjacent elements and swapping any that are out of order. After the first pass, the largest element will have been moved to the end of the list; after the second pass, the second largest will have been moved to the penultimate position; and so forth. The idea is that large values “bubble up” to the top of the list on each pass. A Ruby implementation of bubble sort appears in Figure 1.
    [Show full text]
  • Selection Sort
    CS50 Selection Sort Overview Key Terms Sorted arrays are typically easier to search than unsorted arrays. One algorithm to sort • selection sort is bubble sort. Intuitively, it seemed that there were lots of swaps involved; but perhaps • array there is another way? Selection sort is another sorting algorithm that minimizes the • pseudocode amount of swaps made (at least compared to bubble sort). Like any optimization, ev- erything comes at a cost. While this algorithm may not have to make as many swaps, it does increase the amount of comparing required to sort a single element. Implementation Selection sort works by splitting the array into two parts: a sorted array and an unsorted array. If we are given an array Step-by-step process for of the numbers 5, 1, 6, 2, 4, and 3 and we wanted to sort it selection sort using selection sort, our pseudocode might look something like this: 5 1 6 2 4 3 repeat for the amount of elements in the array find the smallest unsorted value swap that value with the first unsorted value When this is implemented on the example array, the pro- 1 5 6 2 4 3 gram would start at array[0] (which is 5). We would then compare every number to its right (1, 6, 2, 4, and 3), to find the smallest element. Finding that 1 is the smallest, it gets swapped with the element at the current position. Now 1 is 1 2 6 5 4 3 in the sorted part of the array and 5, 6, 2, 4, and 3 are still unsorted.
    [Show full text]
  • Selected Sorting Algorithms
    Selected Sorting Algorithms CS 165: Project in Algorithms and Data Structures Michael T. Goodrich Some slides are from J. Miller, CSE 373, U. Washington Why Sorting? • Practical application – People by last name – Countries by population – Search engine results by relevance • Fundamental to other algorithms • Different algorithms have different asymptotic and constant-factor trade-offs – No single ‘best’ sort for all scenarios – Knowing one way to sort just isn’t enough • Many to approaches to sorting which can be used for other problems 2 Problem statement There are n comparable elements in an array and we want to rearrange them to be in increasing order Pre: – An array A of data records – A value in each data record – A comparison function • <, =, >, compareTo Post: – For each distinct position i and j of A, if i < j then A[i] ≤ A[j] – A has all the same data it started with 3 Insertion sort • insertion sort: orders a list of values by repetitively inserting a particular value into a sorted subset of the list • more specifically: – consider the first item to be a sorted sublist of length 1 – insert the second item into the sorted sublist, shifting the first item if needed – insert the third item into the sorted sublist, shifting the other items as needed – repeat until all values have been inserted into their proper positions 4 Insertion sort • Simple sorting algorithm. – n-1 passes over the array – At the end of pass i, the elements that occupied A[0]…A[i] originally are still in those spots and in sorted order.
    [Show full text]
  • Insertion Sort & Quick Sort
    Department of General and Computational Linguistics Sorting: Insertion Sort & Quick Sort Data Structures and Algorithms for CL III, WS 2019-2020 Corina Dima [email protected] MICHAEL GOODRICH Data Structures & Algorithms in Python ROBERTO TAMASSIA MICHAEL GOLDWASSER 12. Sorting and Selection v Why study sorting algorithms? v Insertion sort (S. 5.5.2) v Quick-sort v Optimizations for quick-sort Sorting: Insertion Sort & Quick Sort | 2 Why Study Sorting Algorithms? • Sorting is among the most important and well studied computing problems • Data is often stored in sorted order, to allow for efficient searching (i.e. with binary search) • Many algorithms rely on sorting as a subroutine • Programming languages have highly optimized, built-in sorting functions – which should be used - Python: sorted(), sort() from the list class - Java: Arrays.sort() Sorting: Insertion Sort & Quick Sort | 3 Why Study Sorting Algorithms? (cont’d) • Understand - what sorting algorithms do - what can be expected in terms of efficiency - how the efficiency of a sorting algorithm can depend on the initial ordering of the data or the type of objects being sorted Sorting: Insertion Sort & Quick Sort | 4 Sorting • Given a collection, rearrange its elements such that they are ordered from smallest to largest – or produce a new copy of the sequence with such an order • We assume that such a consistent order exists • In Python, natural order is typically defined using the < operator, having two properties: - Irreflexive property: " ≮ " - Transitive property:
    [Show full text]
  • Lecture 8.Key
    CSC 391/691: GPU Programming Fall 2015 Parallel Sorting Algorithms Copyright © 2015 Samuel S. Cho Sorting Algorithms Review 2 • Bubble Sort: O(n ) 2 • Insertion Sort: O(n ) • Quick Sort: O(n log n) • Heap Sort: O(n log n) • Merge Sort: O(n log n) • The best we can expect from a sequential sorting algorithm using p processors (if distributed evenly among the n elements to be sorted) is O(n log n) / p ~ O(log n). Compare and Exchange Sorting Algorithms • Form the basis of several, if not most, classical sequential sorting algorithms. • Two numbers, say A and B, are compared between P0 and P1. P0 P1 A B MIN MAX Bubble Sort • Generic example of a “bad” sorting 0 1 2 3 4 5 algorithm. start: 1 3 8 0 6 5 0 1 2 3 4 5 Algorithm: • after pass 1: 1 3 0 6 5 8 • Compare neighboring elements. • Swap if neighbor is out of order. 0 1 2 3 4 5 • Two nested loops. after pass 2: 1 0 3 5 6 8 • Stop when a whole pass 0 1 2 3 4 5 completes without any swaps. after pass 3: 0 1 3 5 6 8 0 1 2 3 4 5 • Performance: 2 after pass 4: 0 1 3 5 6 8 Worst: O(n ) • 2 • Average: O(n ) fin. • Best: O(n) "The bubble sort seems to have nothing to recommend it, except a catchy name and the fact that it leads to some interesting theoretical problems." - Donald Knuth, The Art of Computer Programming Odd-Even Transposition Sort (also Brick Sort) • Simple sorting algorithm that was introduced in 1972 by Nico Habermann who originally developed it for parallel architectures (“Parallel Neighbor-Sort”).
    [Show full text]
  • Advanced Topics in Sorting
    Advanced Topics in Sorting complexity system sorts duplicate keys comparators 1 complexity system sorts duplicate keys comparators 2 Complexity of sorting Computational complexity. Framework to study efficiency of algorithms for solving a particular problem X. Machine model. Focus on fundamental operations. Upper bound. Cost guarantee provided by some algorithm for X. Lower bound. Proven limit on cost guarantee of any algorithm for X. Optimal algorithm. Algorithm with best cost guarantee for X. lower bound ~ upper bound Example: sorting. • Machine model = # comparisons access information only through compares • Upper bound = N lg N from mergesort. • Lower bound ? 3 Decision Tree a < b yes no code between comparisons (e.g., sequence of exchanges) b < c a < c yes no yes no a b c b a c a < c b < c yes no yes no a c b c a b b c a c b a 4 Comparison-based lower bound for sorting Theorem. Any comparison based sorting algorithm must use more than N lg N - 1.44 N comparisons in the worst-case. Pf. Assume input consists of N distinct values a through a . • 1 N • Worst case dictated by tree height h. N ! different orderings. • • (At least) one leaf corresponds to each ordering. Binary tree with N ! leaves cannot have height less than lg (N!) • h lg N! lg (N / e) N Stirling's formula = N lg N - N lg e N lg N - 1.44 N 5 Complexity of sorting Upper bound. Cost guarantee provided by some algorithm for X. Lower bound. Proven limit on cost guarantee of any algorithm for X.
    [Show full text]