Data Structures 5 Sorting Prof A Alkhorabi. 5- 2 Overview Why Sorting? Simple Sorting – Selection & Insertion Sorts Sorting Performance Shell Sort Quicksort.

Slides:



Advertisements
Similar presentations
Sorting Chapter 8 CSCI 3333 Data Structures.
Advertisements

Quick Sort, Shell Sort, Counting Sort, Radix Sort AND Bucket Sort
Sorting. “Sorting” When we just say “sorting,” we mean in ascending order (smallest to largest) The algorithms are trivial to modify if we want to sort.
6-1 CM0551 Week 6 The Array Data Structure Properties of arrays and subarrays – recap. Sorting: insertion, quick-sort and their time and space complexity.
Sorting Algorithms. Motivation Example: Phone Book Searching Example: Phone Book Searching If the phone book was in random order, we would probably never.
Quicksort CS 3358 Data Structures. Sorting II/ Slide 2 Introduction Fastest known sorting algorithm in practice * Average case: O(N log N) * Worst case:
25 May Quick Sort (11.2) CSE 2011 Winter 2011.
Data Structures and Algorithms PLSD210 Sorting. Card players all know how to sort … First card is already sorted With all the rest, ¶Scan back from the.
Ver. 1.0 Session 5 Data Structures and Algorithms Objectives In this session, you will learn to: Sort data by using quick sort Sort data by using merge.
Data Structures Advanced Sorts Part 2: Quicksort Phil Tayco Slide version 1.0 Mar. 22, 2015.
CSE 373: Data Structures and Algorithms
Lecture 25 Selection sort, reviewed Insertion sort, reviewed Merge sort Running time of merge sort, 2 ways to look at it Quicksort Course evaluations.
Quicksort. Quicksort I To sort a[left...right] : 1. if left < right: 1.1. Partition a[left...right] such that: all a[left...p-1] are less than a[p], and.
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. Sorting III 1 An Introduction to Sorting.
Quicksort. 2 Introduction * Fastest known sorting algorithm in practice * Average case: O(N log N) * Worst case: O(N 2 ) n But, the worst case seldom.
CHAPTER 11 Sorting.
Quicksort.
Sorting Chapter 10.
Quicksort.
Unit 061 Quick Sort csc326 Information Structures Spring 2009.
Quicksort
Algorithm Efficiency and Sorting
Sorting CS-212 Dick Steflik. Exchange Sorting Method : make n-1 passes across the data, on each pass compare adjacent items, swapping as necessary (n-1.
Sorting Chapter 10. Chapter 10: Sorting2 Chapter Objectives To learn how to use the standard sorting methods in the Java API To learn how to implement.
CS 202, Spring 2003 Fundamental Structures of Computer Science II Bilkent University1 Sorting - 3 CS 202 – Fundamental Structures of Computer Science II.
(c) , University of Washington
1 Data Structures and Algorithms Sorting. 2  Sorting is the process of arranging a list of items into a particular order  There must be some value on.
Week 11 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
HKOI 2006 Intermediate Training Searching and Sorting 1/4/2006.
Computer Science Searching & Sorting.
Chapter 10 B Algorithm Efficiency and Sorting. © 2004 Pearson Addison-Wesley. All rights reserved 9 A-2 Sorting Algorithms and Their Efficiency Sorting.
LAB#7. Insertion sort In the outer for loop, out starts at 1 and moves right. It marks the leftmost unsorted data. In the inner while loop, in starts.
Sorting Chapter 10. Chapter Objectives  To learn how to use the standard sorting methods in the Java API  To learn how to implement the following sorting.
© 2006 Pearson Addison-Wesley. All rights reserved10 A-1 Chapter 10 Algorithm Efficiency and Sorting.
© 2006 Pearson Addison-Wesley. All rights reserved10 B-1 Chapter 10 (continued) Algorithm Efficiency and Sorting.
Sorting Chapter Sorting Consider list x 1, x 2, x 3, … x n We seek to arrange the elements of the list in order –Ascending or descending Some O(n.
Fundamentals of Algorithms MCS - 2 Lecture # 15. Bubble Sort.
Sorting 2 Taking an arbitrary permutation of n items and rearranging them into total order Sorting is, without doubt, the most fundamental algorithmic.
LAB#6. 2 Overview Before we go to our lesson we must know about : 1. data structure. 2.Algorithms. data structure is an arrangement of data in a computer.
3 – SIMPLE SORTING ALGORITHMS
Review 1 Selection Sort Selection Sort Algorithm Time Complexity Best case Average case Worst case Examples.
Big-O and Sorting February 6, Administrative Stuff Readings for today: Ch Readings for tomorrow: Ch 8.
UNIT 5.  The related activities of sorting, searching and merging are central to many computer applications.  Sorting and merging provide us with a.
Lecture No. 04,05 Sorting.  A process that organizes a collection of data into either ascending or descending order.  Can be used as a first step for.
Sorting and Searching by Dr P.Padmanabham Professor (CSE)&Director
Chapter 9 Sorting 1. The efficiency of data handling can often be increased if the data are sorted according to some criteria of order. The first step.
Chapter 9 Sorting. The efficiency of data handling can often be increased if the data are sorted according to some criteria of order. The first step is.
Data Structures - CSCI 102 Selection Sort Keep the list separated into sorted and unsorted sections Start by finding the minimum & put it at the front.
ICS201 Lecture 21 : Sorting King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Sorting.
Computer Science 1620 Sorting. cases exist where we would like our data to be in ascending (descending order) binary searching printing purposes selection.
PREVIOUS SORTING ALGORITHMS  BUBBLE SORT –Time Complexity: O(n 2 ) For each item, make (n –1) comparisons Gives: Comparisons = (n –1) + (n – 2)
Chapter 9: Sorting1 Sorting & Searching Ch. # 9. Chapter 9: Sorting2 Chapter Outline  What is sorting and complexity of sorting  Different types of.
Sorting Ordering data. Design and Analysis of Sorting Assumptions –sorting will be internal (in memory) –sorting will be done on an array of elements.
Intro. to Data Structures Chapter 7 Sorting Veera Muangsin, Dept. of Computer Engineering, Chulalongkorn University 1 Chapter 7 Sorting Sort is.
Data Structures and Algorithms Instructor: Tesfaye Guta [M.Sc.] Haramaya University.
Bubble Sort Selection Sort Insertion Sort Merge Sort Quick Sort
Quicksort
Description Given a linear collection of items x1, x2, x3,….,xn
Quicksort 1.
Advanced Sorting Methods: Shellsort
Quicksort analysis Bubble sort
CSC215 Lecture Algorithms.
8/04/2009 Many thanks to David Sun for some of the included slides!
Sub-Quadratic Sorting Algorithms
Quicksort.
CSE 373 Data Structures and Algorithms
3 The Array Data Structure
Quicksort.
Quicksort.
Presentation transcript:

Data Structures 5 Sorting Prof A Alkhorabi

5- 2 Overview Why Sorting? Simple Sorting – Selection & Insertion Sorts Sorting Performance Shell Sort Quicksort Merge Sort External Sorting

Prof A Alkhorabi 5- 3 Why Sorting? Sorting is important because sorted data can be searched and merged efficiently. Problem: Given an unsorted array of data, rearrange the data into ascending order. Sorting is a common function in many computer applications: –Transactions are often processed or reported in some sequence, eg. date. –Files are listed in some sequence, eg. alphabetic order or based on file size. –Sorting function may be added as a method in a data structure ADT Efficient sorting of large quantities of data requires some clever algorithms. Some of the most popular search algorithms will be reviewed.

Prof A Alkhorabi 5- 4 Sorting Files vs. Memory Different techniques are often required to sort very large amounts of data stored in a file. The cheapness and large capacities of memories means that most sorting can now be done in the memory. All the algorithms considered assume that the data to be sorted is held in memory.

Prof A Alkhorabi 5- 5 Simple Sorting Algorithms A number of simple sorting algorithms exist: Bubble Sort, bubbles the largest item to the top. After n – 1 passes the list will be sorted. Selection Sort, which works by selecting the smallest item and placing it in the first position and then continuing this process on the remainder of the list. Insertion sort, which works by inserting each item in turn into a partially sorted list.

Prof A Alkhorabi 5- 6 Bubble (Exchange) Sort Algorithm 1.Start with first element in the list 2.Compare this element with next element in the list If this element is less than next element leave it as it is If not, exchange the two elements locations. 3.Repeat (2) for all other elements 4.Repeat (1) to (3) until all elements are sorted. Number of repetitions required = no of elements - 1

Prof A Alkhorabi 5- 7 Sorting using bubble sort Original[ ] FirstRep[ ] Sec. Rep[ ] Third Rep[ ] Fourth Rep[ ] Fifth Rep[ ] Bubble (Exchange) Sort

Prof A Alkhorabi 5- 8 /* Bubble sort: it is an exchange sort, exchanges (swaps) the two adjacent array elements if the second is smaller than the first */ void bubble_sort(int arr[], int elements) { int i, j; void swap(int *num1, int *num2); for(i = 0; i < elements; i++) for(j = 1; j < elements; j++) if(arr[j] < arr[j - 1]) swap(&arr[j], &arr[j-1]); } void swap(int *a, int *b) {int num; num = *a; *a = *b; *b = num; }

Prof A Alkhorabi 5- 9 void print_array(int *p, int elements) { int i; printf("[ "); for(i = 0; i < elements; i++) printf("%d ", p[i]); printf("]\n"); }

Prof A Alkhorabi /* sort_bub.c: Bubble (Exchange) sort Prof Abdullah Alkhorabi */ #include void main() { int array[7] = {15,2,7,4,20,1,10}; void bubble_sort(int arr[], int elements), print_array(int arr[], int elements); printf("Bubble Sort\n"); printf("===========\n"); printf("List before sorting : "); print_array(array, 7); bubble_sort(array, 7); printf("List after sorting : "); print_array(array, 7); }

Prof A Alkhorabi /* sort_bub.cOutput */ Bubble Sort =========== List before sorting : [ ] List after sorting : [ ] Example: Sort_Bub.cppSort_Bub.cpp Time complexity is O(n 2 ).

Prof A Alkhorabi Selection sort (1) Idea: Find the least value in the array, swap it into the leftmost component (where it belongs), and then forget the leftmost component. Do this repeatedly.

Prof A Alkhorabi Selection sort (2) Selection sort algorithm: To sort a[left…right] into ascending order: 1.For l = left, …, right–1, repeat: 1.1.Set p such that a[p] is the least of a[l…right]. 1.2.If p  l, swap a[p] and a[l]. 2.Terminate. Loop invariant: lesser values (sorted)greater values (unsorted) left+1 a lright–1 leftl–1l–1 right

Prof A Alkhorabi To sort a[left…right] into ascending order: 1.For l = left, …, right–1, repeat: 1.1.Set p such that a[p] is the least of a[l…right]. 1.2.If p  l, swap a[p] and a[l]. 2.Terminate. fox left = = right cowpigcatratliontiger a goatdog 67 Selection sort (3) Animation: To sort a[left…right] into ascending order: 1.For l = left, …, right–1, repeat: 1.1.Set p such that a[p] is the least of a[l…right]. 1.2.If p  l, swap a[p] and a[l]. 2.Terminate. fox left = = right cowpigcatratliontiger 0 a l goatdog 67 To sort a[left…right] into ascending order: 1.For l = left, …, right–1, repeat: 1.1.Set p such that a[p] is the least of a[l…right]. 1.2.If p  l, swap a[p] and a[l]. 2.Terminate. fox left = = right cowpigcatratliontiger 0 a l goatdog 67 3 p To sort a[left…right] into ascending order: 1.For l = left, …, right–1, repeat: 1.1.Set p such that a[p] is the least of a[l…right]. 1.2.If p  l, swap a[p] and a[l]. 2.Terminate. cat left = = right cowpigfoxratliontiger 0 a l goatdog 67 3 p To sort a[left…right] into ascending order: 1.For l = left, …, right–1, repeat: 1.1.Set p such that a[p] is the least of a[l…right]. 1.2.If p  l, swap a[p] and a[l]. 2.Terminate. cat left = = right cowpigfoxratliontiger 1 a l goatdog 67 To sort a[left…right] into ascending order: 1.For l = left, …, right–1, repeat: 1.1.Set p such that a[p] is the least of a[l…right]. 1.2.If p  l, swap a[p] and a[l]. 2.Terminate. cat left = = right cowpigfoxratliontiger 1 a l goatdog 67 1 p To sort a[left…right] into ascending order: 1.For l = left, …, right–1, repeat: 1.1.Set p such that a[p] is the least of a[l…right]. 1.2.If p  l, swap a[p] and a[l]. 2.Terminate. cat left = = right cowpigfoxratliontiger 1 a l goatdog 67 1 p To sort a[left…right] into ascending order: 1.For l = left, …, right–1, repeat: 1.1.Set p such that a[p] is the least of a[l…right]. 1.2.If p  l, swap a[p] and a[l]. 2.Terminate. cat left = = right cowpigfoxratliontiger 2 a l goatdog 67 To sort a[left…right] into ascending order: 1.For l = left, …, right–1, repeat: 1.1.Set p such that a[p] is the least of a[l…right]. 1.2.If p  l, swap a[p] and a[l]. 2.Terminate. cat left = = right cowpigfoxratliontiger 2 a l goatdog 67 8 p To sort a[left…right] into ascending order: 1.For l = left, …, right–1, repeat: 1.1.Set p such that a[p] is the least of a[l…right]. 1.2.If p  l, swap a[p] and a[l]. 2.Terminate. cat left = = right cowdogfoxratliontiger 2 a l goatpig 67 8 p To sort a[left…right] into ascending order: 1.For l = left, …, right–1, repeat: 1.1.Set p such that a[p] is the least of a[l…right]. 1.2.If p  l, swap a[p] and a[l]. 2.Terminate. cat left = = right cowdogfoxratliontiger 3 a l goatpig 67 To sort a[left…right] into ascending order: 1.For l = left, …, right–1, repeat: 1.1.Set p such that a[p] is the least of a[l…right]. 1.2.If p  l, swap a[p] and a[l]. 2.Terminate. cat left = = right cowdogfoxratliontiger 3 a l goatpig 67 3 p To sort a[left…right] into ascending order: 1.For l = left, …, right–1, repeat: 1.1.Set p such that a[p] is the least of a[l…right]. 1.2.If p  l, swap a[p] and a[l]. 2.Terminate. cat left = = right cowdogfoxratliontiger 3 a l goatpig 67 3 p To sort a[left…right] into ascending order: 1.For l = left, …, right–1, repeat: 1.1.Set p such that a[p] is the least of a[l…right]. 1.2.If p  l, swap a[p] and a[l]. 2.Terminate. cat left = = right cowdogfoxratliontiger 4 a l goatpig 67 To sort a[left…right] into ascending order: 1.For l = left, …, right–1, repeat: 1.1.Set p such that a[p] is the least of a[l…right]. 1.2.If p  l, swap a[p] and a[l]. 2.Terminate. cat left = = right cowdogfoxratliontiger 4 a l goatpig 67 7 p To sort a[left…right] into ascending order: 1.For l = left, …, right–1, repeat: 1.1.Set p such that a[p] is the least of a[l…right]. 1.2.If p  l, swap a[p] and a[l]. 2.Terminate. cat left = = right cowdogfoxgoatliontiger 4 a l ratpig 67 7 p To sort a[left…right] into ascending order: 1.For l = left, …, right–1, repeat: 1.1.Set p such that a[p] is the least of a[l…right]. 1.2.If p  l, swap a[p] and a[l]. 2.Terminate. cat left = = right cowdogfoxgoatliontiger 5 a l ratpig 67 To sort a[left…right] into ascending order: 1.For l = left, …, right–1, repeat: 1.1.Set p such that a[p] is the least of a[l…right]. 1.2.If p  l, swap a[p] and a[l]. 2.Terminate. cat left = = right cowdogfoxgoatliontiger 5 a l ratpig 67 5 p To sort a[left…right] into ascending order: 1.For l = left, …, right–1, repeat: 1.1.Set p such that a[p] is the least of a[l…right]. 1.2.If p  l, swap a[p] and a[l]. 2.Terminate. cat left = = right cowdogfoxgoatliontiger 5 a l ratpig 67 5 p To sort a[left…right] into ascending order: 1.For l = left, …, right–1, repeat: 1.1.Set p such that a[p] is the least of a[l…right]. 1.2.If p  l, swap a[p] and a[l]. 2.Terminate. cat left = = right cowdogfoxgoatliontiger 6 a l ratpig 67 To sort a[left…right] into ascending order: 1.For l = left, …, right–1, repeat: 1.1.Set p such that a[p] is the least of a[l…right]. 1.2.If p  l, swap a[p] and a[l]. 2.Terminate. cat left = = right cowdogfoxgoatliontiger 6 a l ratpig 67 8 p To sort a[left…right] into ascending order: 1.For l = left, …, right–1, repeat: 1.1.Set p such that a[p] is the least of a[l…right]. 1.2.If p  l, swap a[p] and a[l]. 2.Terminate. cat left = = right cowdogfoxgoatlionpig 6 a l rattiger 67 8 p To sort a[left…right] into ascending order: 1.For l = left, …, right–1, repeat: 1.1.Set p such that a[p] is the least of a[l…right]. 1.2.If p  l, swap a[p] and a[l]. 2.Terminate. cat left = = right cowdogfoxgoatlionpig 7 a l rattiger 67 To sort a[left…right] into ascending order: 1.For l = left, …, right–1, repeat: 1.1.Set p such that a[p] is the least of a[l…right]. 1.2.If p  l, swap a[p] and a[l]. 2.Terminate. cat left = = right cowdogfoxgoatlionpig 7 a l rattiger 67 7 p To sort a[left…right] into ascending order: 1.For l = left, …, right–1, repeat: 1.1.Set p such that a[p] is the least of a[l…right]. 1.2.If p  l, swap a[p] and a[l]. 2.Terminate. cat left = = right cowdogfoxgoatlionpig 7 a l rattiger 67 7 p To sort a[left…right] into ascending order: 1.For l = left, …, right–1, repeat: 1.1.Set p such that a[p] is the least of a[l…right]. 1.2.If p  l, swap a[p] and a[l]. 2.Terminate. cat left = = right cowdogfoxgoatlionpig 8 a l rattiger 67 To sort a[left…right] into ascending order: 1.For l = left, …, right–1, repeat: 1.1.Set p such that a[p] is the least of a[l…right]. 1.2.If p  l, swap a[p] and a[l]. 2.Terminate. cat left = = right cowdogfoxgoatlionpig 8 a l rattiger 67

Prof A Alkhorabi Selection sort (4) Analysis (counting comparisons): Let n = right – left + 1 be the length of the array. Step 1.1 performs right–l comparisons. This is repeated with l = left, …, right–2, right–1. No. of comparisons= (right–left) + … = (n–1) + … * = (n – 1)n/2 = (n 2 – n)/2 Time complexity is O(n 2 ). * Note that the sum of the series 1, 2, …, n–1, n (where n  0) equals n(n + 1)/2.

Prof A Alkhorabi Sorting using selection sort Original[ ] FirstRep[ ] Sec. Rep[ ] Third Rep[ ] Fourth Rep[ ] Fifth Rep[ ] Sixth Rep[ ] Selection Sort

Prof A Alkhorabi /* Selection sort: selects the lowest value element in the rest of the array, and exchange it with the present element */ void selection_sort(int arr[], int elements) { int i, j, minimum, temp; void swap(int *num1, int *num2); for(i = 0; i < elements; i++) { temp = i; minimum = arr[i]; for(j = i+1; j < elements; j++) if(arr[j] < minimum) { minimum = arr[j]; temp = j; } swap(&arr[i], &arr[temp]); }}

Prof A Alkhorabi /* sort_sel.cOutput */ Selection Sort =========== List before sorting : [ ] List after sorting : [ ] Example: SortSel.cppSortSel.cpp

Prof A Alkhorabi Insertion sort (1) Idea: We can sort a file of values by successively reading each value and inserting it into its correct position in an array. Use the same idea to sort an array of values in place.

Prof A Alkhorabi Insertion sort (2) Insertion sort algorithm: To sort a[left…right] into ascending order: 1.For r = left+1, …, right, repeat: 1.1.Let val = a[r]. 1.2.Insert val into its correct sorted position in a[left…r]. 2.Terminate. Loop invariant: inserted (sorted)still to be inserted left+1 a rright–1 leftr–1r–1 right

Prof A Alkhorabi Insertion sort (3) Animation: To sort a[left…right] into ascending order: 1.For r = left+1, …, right, repeat: 1.1.Let val = a[r]. 1.2.Insert val into its correct sorted position in a[left…r]. 2.Terminate. fox left = = right cowpigcatratliontiger a goatdog 67 To sort a[left…right] into ascending order: 1.For r = left+1, …, right, repeat: 1.1.Let val = a[r]. 1.2.Insert val into its correct sorted position in a[left…r]. 2.Terminate. fox left = = right cowpigcatratliontiger 1 a r goatdog 67 To sort a[left…right] into ascending order: 1.For r = left+1, …, right, repeat: 1.1.Let val = a[r]. 1.2.Insert val into its correct sorted position in a[left…r]. 2.Terminate. cow left = = right foxpigcatratliontiger 1 a r goatdog 67 To sort a[left…right] into ascending order: 1.For r = left+1, …, right, repeat: 1.1.Let val = a[r]. 1.2.Insert val into its correct sorted position in a[left…r]. 2.Terminate. cow left = = right foxpigcatratliontiger 2 a r goatdog 67 To sort a[left…right] into ascending order: 1.For r = left+1, …, right, repeat: 1.1.Let val = a[r]. 1.2.Insert val into its correct sorted position in a[left…r]. 2.Terminate. cow left = = right foxpigcatratliontiger 2 a r goatdog 67 To sort a[left…right] into ascending order: 1.For r = left+1, …, right, repeat: 1.1.Let val = a[r]. 1.2.Insert val into its correct sorted position in a[left…r]. 2.Terminate. cow left = = right foxpigcatratliontiger 3 a r goatdog 67 To sort a[left…right] into ascending order: 1.For r = left+1, …, right, repeat: 1.1.Let val = a[r]. 1.2.Insert val into its correct sorted position in a[left…r]. 2.Terminate. cat left = = right cowfoxpigratliontiger 3 a r goatdog 67 To sort a[left…right] into ascending order: 1.For r = left+1, …, right, repeat: 1.1.Let val = a[r]. 1.2.Insert val into its correct sorted position in a[left…r]. 2.Terminate. cat left = = right cowfoxpigratliontiger 4 a r goatdog 67 To sort a[left…right] into ascending order: 1.For r = left+1, …, right, repeat: 1.1.Let val = a[r]. 1.2.Insert val into its correct sorted position in a[left…r]. 2.Terminate. cat left = = right cowfoxpigratliontiger 4 a r goatdog 67 To sort a[left…right] into ascending order: 1.For r = left+1, …, right, repeat: 1.1.Let val = a[r]. 1.2.Insert val into its correct sorted position in a[left…r]. 2.Terminate. cat left = = right cowfoxpigratliontiger 5 a r goatdog 67 To sort a[left…right] into ascending order: 1.For r = left+1, …, right, repeat: 1.1.Let val = a[r]. 1.2.Insert val into its correct sorted position in a[left…r]. 2.Terminate. cat left = = right cowfoxlionpigrattiger 5 a r goatdog 67 To sort a[left…right] into ascending order: 1.For r = left+1, …, right, repeat: 1.1.Let val = a[r]. 1.2.Insert val into its correct sorted position in a[left…r]. 2.Terminate. cat left = = right cowfoxlionpigrattiger 6 a r goatdog 67 To sort a[left…right] into ascending order: 1.For r = left+1, …, right, repeat: 1.1.Let val = a[r]. 1.2.Insert val into its correct sorted position in a[left…r]. 2.Terminate. cat left = = right cowfoxlionpigrattiger 6 a r goatdog 67 To sort a[left…right] into ascending order: 1.For r = left+1, …, right, repeat: 1.1.Let val = a[r]. 1.2.Insert val into its correct sorted position in a[left…r]. 2.Terminate. cat left = = right cowfoxlionpigrattiger 7 a r goatdog 67 To sort a[left…right] into ascending order: 1.For r = left+1, …, right, repeat: 1.1.Let val = a[r]. 1.2.Insert val into its correct sorted position in a[left…r]. 2.Terminate. 7 r 7 r cat left = = right cowfoxgoatlionpigrat a tigerdog 67 cat left = = right cowfoxgoatlionpigrat a tigerdog 67 To sort a[left…right] into ascending order: 1.For r = left+1, …, right, repeat: 1.1.Let val = a[r]. 1.2.Insert val into its correct sorted position in a[left…r]. 2.Terminate. cat left = = right cowfoxgoatlionpigrat 8 a r tigerdog 67 To sort a[left…right] into ascending order: 1.For r = left+1, …, right, repeat: 1.1.Let val = a[r]. 1.2.Insert val into its correct sorted position in a[left…r]. 2.Terminate. cat left = = right cowdogfoxgoatlionpig 8 a r rattiger 67 To sort a[left…right] into ascending order: 1.For r = left+1, …, right, repeat: 1.1.Let val = a[r]. 1.2.Insert val into its correct sorted position in a[left…r]. 2.Terminate. cat left = = right cowdogfoxgoatlionpig 9 a r rattiger 67 To sort a[left…right] into ascending order: 1.For r = left+1, …, right, repeat: 1.1.Let val = a[r]. 1.2.Insert val into its correct sorted position in a[left…r]. 2.Terminate. cat left = = right cowdogfoxgoatlionpig a rattiger 67

Prof A Alkhorabi Insertion sort (4) Analysis (counting comparisons): Let n = right – left + 1 be the length of the array. Step 1.2 performs between 1 and r – left comparisons, say (r – left + 1)/2 comparisons on average. This is repeated with r = left+1, left+2, …, right. Average no. of comparisons= 2/2 + 3/2 + … + n/2 = (n – 1)(n + 2)/4 = (n 2 + n – 2)/4 Time complexity is O(n 2 ).

Prof A Alkhorabi Sorting using insersion sort Original[ ] FirstRep[ ] Sec. Rep[ ] Third Rep[ ] Fourth Rep[ ] Fifth Rep[ ] Sixth Rep[ ]

Prof A Alkhorabi /* Insertion sort : First swaps the first two array elements if the second is smaller, then each element in the rest of the array is inserted within the sorted elements */ void insertion_sort(int arr[], int elements) { int i, j, temp; void shift_array(int array[], int a, int b); for(i = 1; i < elements; i++) { for(j = 0; j < i; j++) if(arr[j] > arr[i]) { temp = arr[i]; shift_array(arr, j, i); arr[j] = temp; break;} } }

Prof A Alkhorabi /* Shifts the subarray part lies between 'a' and 'b' one position */ void shift_array(int *array, int a, int b) { int i; for(i = b; i >= a; i--) array[i] = array[i-1]; }

Prof A Alkhorabi /* sort_ins.cOutput */ Insertion Sort =========== List before sorting : [ ] List after sorting : [ ] Example: Sort_Ins.cppSort_Ins.cpp

Prof A Alkhorabi Sorting Performance We measure the performance of a sorting algorithm in terms of the number of comparisons that must be done. For a Bubble Sort, every element is compared with every other element, so this is O(n 2 ). For Selection Sort, the number of comparisons is slightly less, but for a large data set it is still quite close to n 2 and we say it is still O(n 2 ). The same applies with Insertion Sort except that the inner loop will terminate early if the data is already in order. So for a pre- sorted input, the performance is O(n), but the average performance is still O(n 2 ).

Prof A Alkhorabi Improved Sorting Algorithms In order to achieve better than O(n 2 ) performance it is necessary to swap elements that are not adjacent. We following two algorithms do this: –Shellsort (named after Donald Shell) is essentially an Insertion Sort that looks at items some distance apart. Each pass reduces this distance and the last pass looks at adjacent items (and is therefore an Insertion Sort). –Quicksort is the fastest known algorithm in practice and works by partitioning the data and recursively sorting smaller partitions.

Prof A Alkhorabi Quick Sort Basic strategy is divide & conquer (recursive): –Pick a random element – the pivot. –Partition the elements into those greater than and those less than the pivot. This is the difficult part! –Do this recursively on each of the two partitions while the number of elements in a partition is more than 1.

Prof A Alkhorabi Quick-sort (1) Idea: Choose any value from the array (called the pivot). Then partition the array into three subarrays such that: –the left subarray contains only values less than (or equal to) the pivot; –the middle subarray contains only the pivot; –the right subarray contains only values greater than (or equal to) the pivot. Finally sort the left subarray and the right subarray separately. This is another application of the divide-and-conquer strategy.

Prof A Alkhorabi Quick-sort (2) Quick-sort algorithm: To sort a[left…right] into ascending order: 1.Select a[p]: 1.1.Partition a[left…right] such that a[left…p–1] are all less than or equal to a[p], and a[p+1…right] are all greater than or equal to a[p]. 1.2.Sort a[left…p–1] into ascending order. 1.3.Sort a[p+1…right] into ascending order. 2.Terminate.

Prof A Alkhorabi Quick-sort (3) Invariants: After step 1.1: p+1 a p leftp–1p–1 right After step 1.3: p+1 a p leftp–1p–1 right less than or equal to pivot (unsorted) pivotgreater than or equal to pivot (unsorted) less than or equal to pivot (sorted) pivotgreater than or equal to pivot (sorted)

Prof A Alkhorabi Quick-sort (4) Animation: To sort a[left…right] into ascending order: 1.If left < right: 1.1.Partition a[left…right] such that a[left…p–1] are all less than or equal to a[p], and a[p+1…right] are all greater than or equal to a[p]. 1.2.Sort a[left…p–1] into ascending order. 1.3.Sort a[p+1…right] into ascending order. 2.Terminate. fox left = = right cowpigcatratliontiger a goatdog 67 To sort a[left…right] into ascending order: 1.If left < right: 1.1.Partition a[left…right] such that a[left…p–1] are all less than or equal to a[p], and a[p+1…right] are all greater than or equal to a[p]. 1.2.Sort a[left…p–1] into ascending order. 1.3.Sort a[p+1…right] into ascending order. 2.Terminate. fox left = = right cowpigcatratliontiger a goatdog 67 To sort a[left…right] into ascending order: 1.If left < right: 1.1.Partition a[left…right] such that a[left…p–1] are all less than or equal to a[p], and a[p+1…right] are all greater than or equal to a[p]. 1.2.Sort a[left…p–1] into ascending order. 1.3.Sort a[p+1…right] into ascending order. 2.Terminate. cow left = = right catdogfoxpigratlion a tigergoat 67 3 p To sort a[left…right] into ascending order: 1.If left < right: 1.1.Partition a[left…right] such that a[left…p–1] are all less than or equal to a[p], and a[p+1…right] are all greater than or equal to a[p]. 1.2.Sort a[left…p–1] into ascending order. 1.3.Sort a[p+1…right] into ascending order. 2.Terminate. cat left = = right cowdogfoxpigratlion a tigergoat 67 3 p To sort a[left…right] into ascending order: 1.If left < right: 1.1.Partition a[left…right] such that a[left…p–1] are all less than or equal to a[p], and a[p+1…right] are all greater than or equal to a[p]. 1.2.Sort a[left…p–1] into ascending order. 1.3.Sort a[p+1…right] into ascending order. 2.Terminate. cat left = = right cowdogfoxgoatlionpig a rattiger 67 3 p To sort a[left…right] into ascending order: 1.Select pivot a[p]: 1.1.Partition a[left…right] such that a[left…p–1] are all less than or equal to a[p], and a[p+1…right] are all greater than or equal to a[p]. 1.2.Sort a[left…p–1] into ascending order. 1.3.Sort a[p+1…right] into ascending order. 2.Terminate. cat left = = right cowdogfoxgoatlionpig a rattiger 67

Prof A Alkhorabi Sorting using quick sort Original[ ] FirstRep[ ] SecRep[ ] Quick-sort (4)

Prof A Alkhorabi Quick-sort (5) Analysis (counting comparisons): Let n be the no. of values to be sorted. Let the total no. of comparisons required to sort n values be comps(n). Step 1.1 takes about n–1 comparisons to partition the array. (NB: partition, not sort!)

Prof A Alkhorabi Quick-sort (6) In the best case, the pivot turns out to be the median value in the array. So the left and right subarrays both have length about n/2. Then steps 1.2 and 1.3 take about comps(n/2) comparisons each. Therefore: comps(n)  2 comps(n/2) + n – 1if n > 1 comps(n) = 0if n  1 Solution: comps(n)  n log 2 n Best-case time complexity is O(n log n).

Prof A Alkhorabi Quick-sort (7) In the worst case, the pivot turns out to be the smallest value. So the right subarray has length n–1 whilst the left subarray has length 0. Then step 1.3 performs comps(n–1) comparisons, but step 1.2 does nothing at all. Therefore: comps(n)  comps(n–1) + n – 1if n > 1 comps(n) = 0if n  1 Solution: comps(n)  (n 2 – n)/2 Worst-case time complexity is O(n 2 ). The worst case arises if the array is already sorted!

Prof A Alkhorabi Quick-sort (8) /* Quick sort : First select a pivot (mean of the first three elements or simply the first element). Start from the second array element, put all elements of the array less than pivot left of the pivot and the rest to the right of it. Do the same (recursively) to the right and to the left lists. */ void quick_sort(int arr[], int first, int last) { int i, j, pivot, previous, middle, temp; i = first; j = last; middle = arr[(first+last)/2]; do { while(arr[i] < middle && i < last) i++; while(middle first) j--; if(i <= j) { swap(&arr[j], &arr[i]); i++; j--; } }while (i <= j); if ( first < j ) quick_sort(arr, first, j); if ( i < last ) quick_sort(arr, i, last); }

Prof A Alkhorabi /* Output of sort_qck.c [ ] [ ] Example: Sort_Qck.cppSort_Qck.cpp

Prof A Alkhorabi Quick-sort Performance The performance is O(n log n) if the algorithm is coded carefully. A bad choice of pivot can result in O(n 2 ) performance. Suppose that sorting 1,000 items takes seconds. What is the big deal about performance? Does it really matter much? However, if we were to now sort 1,000,000 items with an O(n 2 ) algorithm like Insertion sort, it would take about 1000 seconds (nearly 17 minutes). If we instead used an O(n log n) algorithm like Quicksort sorting 1,000,000 items would take about 2 seconds – a significant improvement!

Prof A Alkhorabi Comparison of sorting algorithms AlgorithmNo. of comparisons No. of copies Time complexity Space complexity Selection sort~ n 2 /2~ 2nO(n2)O(n2)O(1) Insertion sort~ n 2 /4 O(n2)O(n2)O(1) Quick-sort~ n log 2 n ~ n 2 /2 ~ 2n/3 log 2 n 0 O(n log n) O(n 2 ) O(log n) O(n) best worst Example: AllSortingAlgorithms.cppAllSortingAlgorithms.cpp

Prof A Alkhorabi Exercise: Write an algorithm and a C++ program that sorts the array of the following array of strings using Quick Sort for strings: ["fox","cow","pig","cat","rat","lion","tiger","goat","dog"] HINT: First select a pivot (mean of the first three elements or simply the first element). Start from the second array element, put all elements of the array less than pivot left of the pivot and the rest to the right of it. Do the same (recursively) to the right and the left lists.