Sorting Algorithms

Total Page:16

File Type:pdf, Size:1020Kb

Sorting Algorithms Sorting Algorithms We have already seen: I Selection-sort I Insertion-sort I Heap-sort We will see: I Bubble-sort I Merge-sort I Quick-sort We will show that: I O(n · log n) is optimal for comparison based sorting. Bubble-Sort The basic idea of bubble-sort is as follows: I exchange neighboring elements that are in wrong order I stops when no elements were exchanged bubbleSort(A): n = length(A) swapped = true while swapped == true do swapped = false for i = 0 to n - 2 do if A[i] > A[i + 1] then swap(A[i]; A[i + 1]) swapped = true done n = n - 1 done Bubble-Sort: Example 5 4 3 7 1 Unsorted Part 4 5 3 7 1 Sorted Part 4 3 5 7 1 4 3 5 7 1 4 3 5 1 7 3 4 5 1 7 4 3 5 1 7 4 3 1 5 7 3 4 1 5 7 3 1 4 5 7 1 3 4 5 7 Bubble-Sort: Properties Time complexity: I worst-case: (n - 1)2 + n - 1 (n - 1) + ::: + 1 = 2 O(n2) 2 (caused by sorting an inverse sorted list) I best-case: O(n) Bubble-sort is: I slow I in-place Divide-and-Conquer Divide-and-Conquer is a general algorithm design paradigm: I Divide: divide the input S into two disjoint subsets S1, S2 I Recur: recursively solve the subproblems S1, S2 I Conquer: combine solutions for S1, S2 to a solution for S (the base case of the recursion are problems of size 0 or 1) Example: merge-sort 7 2 j 9 4 7 2 4 7 9 7 j 2 7 2 7 9 j 4 7 4 9 ! 7 7 7 2 7 2 9 7 9 4 7 4 ! ! I j indicates! the splitting! point ! ! I 7 indicates merging of the sub-solutions ! Merge Sort Merge-sort of a list S with n elements works as follows: I Divide: divide S into two lists S1, S2 of ≈ n=2 elements I Recur: recursively sort S1, S2 I Conquer: merge S1 and S2 into a sorting of S Algorithm mergeSort(S; C): Input: a list S of n elements and a comparator C Output: the list S sorted according to C if size(S) > 1 then (S1; S2) = partition S into size bn=2c and dn=2e mergeSort(S1; C) mergeSort(S2; C) S = merge(S1; S2; C) Merging two Sorted Sequences Algorithm merge(A; B; C): Input: sorted lists A, B Output: sorted lists containing the elements of A and B S = empty list while :A:isEmtpy() or :B:isEmtpy() do if A:first():element < B:first():element then S:insertLast(A:remove(A:first())) else S:insertLast(B:remove(B:first())) done while :A:isEmtpy() do S:insertLast(A:remove(A:first())) while :B:isEmtpy() do S:insertLast(B:remove(B:first())) Performance: I Merging two sorted lists of length about n=2 is O(n) time. (for singly linked lists, double linked lists, and arrays) Merge-sort: Example a n e x j a m p l e Divide (split) a n j e x a m j p l e a j n e j x a j m p j l e a n e x a m p l j e Conquer l e (merge) a n e x a m e l a e n x e l p a e l m p a a e e l m n p x Merge-Sort Tree An execution of merge-sort can be displayed in a binary tree: I each node represents recursive call and stores: I unsorted sequence before execution, its partition I sorted sequence after execution I leaves are calls on subsequences of size 0 or 1 a n e x j a m p l e 7 a a e e l m n p x a n j e x 7 a e n x ! a m j p l e 7 a e l m p a j n 7 a n ! e j x 7 e x a j m 7 a m ! p j l e 7 e l p a 7 a!n 7 n e 7 e!x 7 x a 7 a !m 7 m p 7 p !l j e 7 e l ! ! ! ! ! ! ! l 7 l !e 7 e ! ! Merge-Sort: Example Execution 7 1 2 9 j 6 5 3 8 7 1 2 3 5 6 7 8 9 7 1 j 2 9 7 1 2 7 9 ! 6 5 j 3 8 7 3 5 6 8 7 j 1 7 1 7 ! 2 j 9 7 2 9 6 j 5 7 5 6 ! 3 j 8 7 3 8 7 7 7!1 7 1 2 7 2!9 7 9 6 7 6!5 7 5 3 7 3!8 7 8 ! ! ! ! ! ! ! ! Finished merge-sort tree. Merge-Sort: Running Time The height h of the merge-sort tree is O(log2 n): I each recursive call splits the sequence in half The work all nodes together at depth i is O(n): i i I partitioning, and merging of 2 sequences of n=2 i+1 I 2 ≤ n recursive calls depth nodes size 0 1 n 1 2 n=2 i 2i n=2i ... ... ... Thus the worst-case running time is O(n · log2 n). Quick-Sort Quick-sort of a list S with n elements works as follows: I Divide: pick random element x (pivot) from S and split S in: I L elements less than x I E elements equal than x I G elements greater than x 7 2 1 9 6 5 3 8 I Recur: recursively sort L, and G 2 1 3 5 7 9 6 8 L E G I Conquer: join L, E, and G 1 2 3 5 6 7 8 9 Quick-Sort: The Partitioning The partitioning runs in O(n) time: I we traverse S and compare every element y with x I depending on the comparison insert y in L, E or G Algorithm partition(S; p): Input: a list S of n elements, and positon p of the pivot Output: list L, E, G of lists less, equal or greater than pivot L; E; G = empty lists x = S:elementAtRank(p) while :S:isEmpty() do y = S:remove(S:first()) if y < x then L:insertLast(y) if y == x then E:insertLast(y) if y > x then G:insertLast(y) done return L; E; G Quick-Sort Tree An execution of quick-sort can be displayed in a binary tree: I each node represents recursive call and stores: I unsorted sequence before execution, and its pivot I sorted sequence after execution I leaves are calls on subsequences of size 0 or 1 1 6 2 940 7 0 1 2469 120 7 012 ! 69 7 69 0 7 0 ! 2 7 2 ! 9 7 9 ! ! ! Quick-Sort: Example 8 2 9 3 1 5 764 7 1 2 3 4 56789 2 3154 7 12345 ! 897 7 789 !2354 7 2345 7 7 7 ! 9 7 9 2 7 2 ! 54 7 45 ! ! ! 4 7 4! ! Quick-Sort: Worst-Case Running Time The worst-case running time occurs when: I the pivot is always the minimal or maximal element I then one L and G has size n - 1, the other size 0 Then the running time is O(n2): n + (n - 1) + (n - 2) + ::: + 1 2 O(n2) n 0 n - 1 0 n - 2 . 0 . 1 0 0 Quick-Sort: Average Running Time Consider a recursive call on a list of size m: 3 I Good call: if both L and G are each less then 4 · s size 3 I Bad call: one of L and G is greater than 4 · s size 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 bad calls good calls bad calls 1 A good call has probability 2 : I half of the pivots give rise to good calls Quick-Sort: Average Running Time For a node at depth i, we expect (average): I i=2 ancestors are good calls i=2 I the size of the sequence is ≤ (3=4) · n As a consequence: I for a node at depth 2 · log3=4 n the expected input size is 1 I the expected height of the quick-sort tree is O(log n) sa O(n) sb sc O(n) O(log n) sd se sf sg O(n) ... ... ... ... ... ... ... ... The amount of work at depth i is O(n). Thus the expected (average) running time is O(n · log n). In-Place Quick-Sort Quick-Sort can be sorted in-place (but then non-stable): Algorithm inPlaceQuickSort(A; l; r): Input: list A, indices l and r Output: list A where elements from index l to r are sorted if l ≥ r then return p = A[r] (take rightmost element as pivot) l0 = l and r 0 = r while l0 ≤ r 0 do while l0 ≤ r 0 and A[l0] ≤ p do l0 = l0 + 1 (find > p) while l0 ≤ r 0 and A[r 0] ≥ p do r 0 = r 0 - 1 (find < p) if l0 < r 0 then swap(A[l0]; A[r 0]) (swap < p with > p) done swap(A[r]; A[l0]) (put pivot into the right place) inPlaceQuickSort(A; l; l0 - 1) (sort left part) inPlaceQuickSort(A; l0 + 1; r) (sort right part) Considered in-place although recursion needs O(log n) space.
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]
  • CS 758/858: Algorithms
    CS 758/858: Algorithms ■ COVID Prof. Wheeler Ruml Algorithms TA Sumanta Kashyapi This Class Complexity http://www.cs.unh.edu/~ruml/cs758 4 handouts: course info, schedule, slides, asst 1 2 online handouts: programming tips, formulas 1 physical sign-up sheet/laptop (for grades, piazza) Wheeler Ruml (UNH) Class 1, CS 758 – 1 / 25 COVID ■ COVID Algorithms This Class Complexity ■ check your Wildcat Pass before coming to campus ■ if you have concerns, let me know Wheeler Ruml (UNH) Class 1, CS 758 – 2 / 25 ■ COVID Algorithms ■ Algorithms Today ■ Definition ■ Why? ■ The Word ■ The Founder This Class Complexity Algorithms Wheeler Ruml (UNH) Class 1, CS 758 – 3 / 25 Algorithms Today ■ ■ COVID web: search, caching, crypto Algorithms ■ networking: routing, synchronization, failover ■ Algorithms Today ■ machine learning: data mining, recommendation, prediction ■ Definition ■ Why? ■ bioinformatics: alignment, matching, clustering ■ The Word ■ ■ The Founder hardware: design, simulation, verification ■ This Class business: allocation, planning, scheduling Complexity ■ AI: robotics, games Wheeler Ruml (UNH) Class 1, CS 758 – 4 / 25 Definition ■ COVID Algorithm Algorithms ■ precisely defined ■ Algorithms Today ■ Definition ■ mechanical steps ■ Why? ■ ■ The Word terminates ■ The Founder ■ input and related output This Class Complexity What might we want to know about it? Wheeler Ruml (UNH) Class 1, CS 758 – 5 / 25 Why? ■ ■ COVID Computer scientist 6= programmer Algorithms ◆ ■ Algorithms Today understand program behavior ■ Definition ◆ have confidence in results, performance ■ Why? ■ The Word ◆ know when optimality is abandoned ■ The Founder ◆ solve ‘impossible’ problems This Class ◆ sets you apart (eg, Amazon.com) Complexity ■ CPUs aren’t getting faster ■ Devices are getting smaller ■ Software is the differentiator ■ ‘Software is eating the world’ — Marc Andreessen, 2011 ■ Everything is computation Wheeler Ruml (UNH) Class 1, CS 758 – 6 / 25 The Word: Ab¯u‘Abdall¯ah Muh.ammad ibn M¯us¯aal-Khw¯arizm¯ı ■ COVID 780-850 AD Algorithms Born in Uzbekistan, ■ Algorithms Today worked in Baghdad.
    [Show full text]
  • Overview Parallel Merge Sort
    CME 323: Distributed Algorithms and Optimization, Spring 2015 http://stanford.edu/~rezab/dao. Instructor: Reza Zadeh, Matriod and Stanford. Lecture 4, 4/6/2016. Scribed by Henry Neeb, Christopher Kurrus, Andreas Santucci. Overview Today we will continue covering divide and conquer algorithms. We will generalize divide and conquer algorithms and write down a general recipe for it. What's nice about these algorithms is that they are timeless; regardless of whether Spark or any other distributed platform ends up winning out in the next decade, these algorithms always provide a theoretical foundation for which we can build on. It's well worth our understanding. • Parallel merge sort • General recipe for divide and conquer algorithms • Parallel selection • Parallel quick sort (introduction only) Parallel selection involves scanning an array for the kth largest element in linear time. We then take the core idea used in that algorithm and apply it to quick-sort. Parallel Merge Sort Recall the merge sort from the prior lecture. This algorithm sorts a list recursively by dividing the list into smaller pieces, sorting the smaller pieces during reassembly of the list. The algorithm is as follows: Algorithm 1: MergeSort(A) Input : Array A of length n Output: Sorted A 1 if n is 1 then 2 return A 3 end 4 else n 5 L mergeSort(A[0, ..., 2 )) n 6 R mergeSort(A[ 2 , ..., n]) 7 return Merge(L, R) 8 end 1 Last lecture, we described one way where we can take our traditional merge operation and translate it into a parallelMerge routine with work O(n log n) and depth O(log n).
    [Show full text]
  • Bubble Sort: an Archaeological Algorithmic Analysis
    Bubble Sort: An Archaeological Algorithmic Analysis Owen Astrachan 1 Computer Science Department Duke University [email protected] Abstract 1 Introduction Text books, including books for general audiences, in- What do students remember from their first program- variably mention bubble sort in discussions of elemen- ming courses after one, five, and ten years? Most stu- tary sorting algorithms. We trace the history of bub- dents will take only a few memories of what they have ble sort, its popularity, and its endurance in the face studied. As teachers of these students we should ensure of pedagogical assertions that code and algorithmic ex- that what they remember will serve them well. More amples used in early courses should be of high quality specifically, if students take only a few memories about and adhere to established best practices. This paper is sorting from a first course what do we want these mem- more an historical analysis than a philosophical trea- ories to be? Should the phrase Bubble Sort be the first tise for the exclusion of bubble sort from books and that springs to mind at the end of a course or several courses. However, sentiments for exclusion are sup- years later? There are compelling reasons for excluding 1 ported by Knuth [17], “In short, the bubble sort seems discussion of bubble sort , but many texts continue to to have nothing to recommend it, except a catchy name include discussion of the algorithm after years of warn- and the fact that it leads to some interesting theoreti- ings from scientists and educators.
    [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]
  • Sorting Partnership Unless You Sign Up! Brian Curless • Homework #5 Will Be Ready After Class, Spring 2008 Due in a Week
    Announcements (5/9/08) • Project 3 is now assigned. CSE 326: Data Structures • Partnerships due by 3pm – We will not assume you are in a Sorting partnership unless you sign up! Brian Curless • Homework #5 will be ready after class, Spring 2008 due in a week. • Reading for this lecture: Chapter 7. 2 Sorting Consistent Ordering • Input – an array A of data records • The comparison function must provide a – a key value in each data record consistent ordering on the set of possible keys – You can compare any two keys and get back an – a comparison function which imposes a indication of a < b, a > b, or a = b (trichotomy) consistent ordering on the keys – The comparison functions must be consistent • Output • If compare(a,b) says a<b, then compare(b,a) must say b>a • If says a=b, then must say b=a – reorganize the elements of A such that compare(a,b) compare(b,a) • If compare(a,b) says a=b, then equals(a,b) and equals(b,a) • For any i and j, if i < j then A[i] ≤ A[j] must say a=b 3 4 Why Sort? Space • How much space does the sorting • Allows binary search of an N-element algorithm require in order to sort the array in O(log N) time collection of items? • Allows O(1) time access to kth largest – Is copying needed? element in the array for any k • In-place sorting algorithms: no copying or • Sorting algorithms are among the most at most O(1) additional temp space.
    [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]
  • Chapter 19 Searching, Sorting and Big —Solutions
    With sobs and tears he sorted out Those of the largest size … —Lewis Carroll Attempt the end, and never stand to doubt; Nothing’s so hard, but search will find it out. —Robert Herrick ’Tis in my memory lock’d, And you yourself shall keep the key of it. —William Shakespeare It is an immutable law in business that words are words, explanations are explanations, promises are promises — but only performance is reality. —Harold S. Green In this Chapter you’ll learn: ■ To search for a given value in an array using linear search and binary search. ■ To sort arrays using the iterative selection and insertion sort algorithms. ■ To sort arrays using the recursive merge sort algorithm. ■ To determine the efficiency of searching and sorting algorithms. © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved. 2 Chapter 19 Searching, Sorting and Big —Solutions Self-Review Exercises 19.1 Fill in the blanks in each of the following statements: a) A selection sort application would take approximately times as long to run on a 128-element array as on a 32-element array. ANS: 16, because an O(n2) algorithm takes 16 times as long to sort four times as much in- formation. b) The efficiency of merge sort is . ANS: O(n log n). 19.2 What key aspect of both the binary search and the merge sort accounts for the logarithmic portion of their respective Big Os? ANS: Both of these algorithms incorporate “halving”—somehow reducing something by half. The binary search eliminates from consideration one-half of the array after each comparison.
    [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]
  • Sorting Algorithm 1 Sorting Algorithm
    Sorting algorithm 1 Sorting algorithm In computer science, a sorting algorithm is an algorithm that puts elements of a list in a certain order. The most-used orders are numerical order and lexicographical order. Efficient sorting is important for optimizing the use of other algorithms (such as search and merge algorithms) that require sorted lists to work correctly; it is also often useful for canonicalizing data and for producing human-readable output. More formally, the output must satisfy two conditions: 1. The output is in nondecreasing order (each element is no smaller than the previous element according to the desired total order); 2. The output is a permutation, or reordering, of the input. Since the dawn of computing, the sorting problem has attracted a great deal of research, perhaps due to the complexity of solving it efficiently despite its simple, familiar statement. For example, bubble sort was analyzed as early as 1956.[1] Although many consider it a solved problem, useful new sorting algorithms are still being invented (for example, library sort was first published in 2004). Sorting algorithms are prevalent in introductory computer science classes, where the abundance of algorithms for the problem provides a gentle introduction to a variety of core algorithm concepts, such as big O notation, divide and conquer algorithms, data structures, randomized algorithms, best, worst and average case analysis, time-space tradeoffs, and lower bounds. Classification Sorting algorithms used in computer science are often classified by: • Computational complexity (worst, average and best behaviour) of element comparisons in terms of the size of the list . For typical sorting algorithms good behavior is and bad behavior is .
    [Show full text]
  • Sorting Algorithms
    Sorting Algorithms Chapter 12 Our first sort: Selection Sort • General Idea: min SORTED UNSORTED SORTED UNSORTED What is the invariant of this sort? Selection Sort • Let A be an array of n ints, and we wish to sort these keys in non-decreasing order. • Algorithm: for i = 0 to n-2 do find j, i < j < n-1, such that A[j] < A[k], k, i < k < n-1. swap A[j] with A[i] • This algorithm works in place, meaning it uses its own storage to perform the sort. Selection Sort Example 66 44 99 55 11 88 22 77 33 11 44 99 55 66 88 22 77 33 11 22 99 55 66 88 44 77 33 11 22 33 55 66 88 44 77 99 11 22 33 44 66 88 55 77 99 11 22 33 44 55 88 66 77 99 11 22 33 44 55 66 88 77 99 11 22 33 44 55 66 77 88 99 11 22 33 44 55 66 77 88 99 Selection Sort public static void sort (int[] data, int n) { int i,j,minLocation; for (i=0; i<=n-2; i++) { minLocation = i; for (j=i+1; j<=n-1; j++) if (data[j] < data[minLocation]) minLocation = j; swap(data, minLocation, i); } } Run time analysis • Worst Case: Search for 1st min: n-1 comparisons Search for 2nd min: n-2 comparisons ... Search for 2nd-to-last min: 1 comparison Total comparisons: (n-1) + (n-2) + ... + 1 = O(n2) • Average Case and Best Case: O(n2) also! (Why?) Selection Sort (another algorithm) public static void sort (int[] data, int n) { int i, j; for (i=0; i<=n-2; i++) for (j=i+1; j<=n-1; j++) if (data[j] < data[i]) swap(data, i, j); } Is this any better? Insertion Sort • General Idea: SORTED UNSORTED SORTED UNSORTED What is the invariant of this sort? Insertion Sort • Let A be an array of n ints, and we wish to sort these keys in non-decreasing order.
    [Show full text]