C Programming Week 10 Sorting Algorithms 1. Sorting In many queries we handle a list of values and want a specific value. We can go through all the list.

Slides:



Advertisements
Similar presentations
Chapter 9 continued: Quicksort
Advertisements

Introduction to Algorithms Quicksort
Garfield AP Computer Science
Sorting Sorting is the process of arranging a list of items in a particular order The sorting process is based on specific value(s) Sorting a list of test.
QuickSort 4 February QuickSort(S) Fast divide and conquer algorithm first discovered by C. A. R. Hoare in If the number of elements in.
Quicksort CS 3358 Data Structures. Sorting II/ Slide 2 Introduction Fastest known sorting algorithm in practice * Average case: O(N log N) * Worst case:
CS 206 Introduction to Computer Science II 04 / 28 / 2009 Instructor: Michael Eckmann.
25 May Quick Sort (11.2) CSE 2011 Winter 2011.
QuickSort The content for these slides was originally created by Gerard Harrison. Ported to C# by Mike Panitz.
Quicksort, Mergesort, and Heapsort. Quicksort Fastest known sorting algorithm in practice  Caveats: not stable  Vulnerable to certain attacks Average.
Updated QuickSort Problem From a given set of n integers, find the missing integer from 0 to n using O(n) queries of type: “what is bit[j]
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.
CS203 Programming with Data Structures Sorting California State University, Los Angeles.
 1 Sorting. For computer, sorting is the process of ordering data. [ ]  [ ] [ “Tom”, “Michael”, “Betty” ]  [ “Betty”, “Michael”,
CS 206 Introduction to Computer Science II 12 / 09 / 2009 Instructor: Michael Eckmann.
Recitation 9 Programming for Engineers in Python.
Lecture 25 Selection sort, reviewed Insertion sort, reviewed Merge sort Running time of merge sort, 2 ways to look at it Quicksort Course evaluations.
1 Sorting Algorithms (Part II) Overview  Divide and Conquer Sorting Methods.  Merge Sort and its Implementation.  Brief Analysis of Merge Sort.  Quick.
Chapter 11 Sorting and Searching. Copyright © 2005 Pearson Addison-Wesley. All rights reserved Chapter Objectives Examine the linear search and.
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.
1 Algorithm Efficiency and Sorting (Walls & Mirrors - Remainder of Chapter 9)
CHAPTER 11 Sorting.
Quicksort.
Divide and Conquer The most well known algorithm design strategy: 1. Divide instance of problem into two or more smaller instances 2. Solve smaller instances.
CS 206 Introduction to Computer Science II 12 / 08 / 2008 Instructor: Michael Eckmann.
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.
CIS 068 Welcome to CIS 068 ! Lesson 9: Sorting. CIS 068 Overview Algorithmic Description and Analysis of Selection Sort Bubble Sort Insertion Sort Merge.
Sorting HKOI Training Team (Advanced)
Computer Science 101 Fast Searching and Sorting. Improving Efficiency We got a better best case by tweaking the selection sort and the bubble sort We.
HKOI 2006 Intermediate Training Searching and Sorting 1/4/2006.
1 Lecture 16: Lists and vectors Binary search, Sorting.
Computer Science Searching & Sorting.
Quicksort, Mergesort, and Heapsort. Quicksort Fastest known sorting algorithm in practice  Caveats: not stable  Vulnerable to certain attacks Average.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 19: Searching and Sorting.
Order Statistics. Order statistics Given an input of n values and an integer i, we wish to find the i’th largest value. There are i-1 elements smaller.
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.
© M. Gross, ETH Zürich, 2014 Informatik I für D-MAVT (FS 2014) Exercise 12 – Data Structures – Trees Sorting Algorithms.
1 Sorting Algorithms Sections 7.1 to Comparison-Based Sorting Input – 2,3,1,15,11,23,1 Output – 1,1,2,3,11,15,23 Class ‘Animals’ – Sort Objects.
Chapter 8 Sorting and Searching Goals: 1.Java implementation of sorting algorithms 2.Selection and Insertion Sorts 3.Recursive Sorts: Mergesort and Quicksort.
Review 1 Selection Sort Selection Sort Algorithm Time Complexity Best case Average case Worst case Examples.
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.
1 Searching and Sorting Searching algorithms with simple arrays Sorting algorithms with simple arrays –Selection Sort –Insertion Sort –Bubble Sort –Quick.
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.
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)
Quicksort This is probably the most popular sorting algorithm. It was invented by the English Scientist C.A.R. Hoare It is popular because it works well.
Quicksort Dr. Yingwu Zhu. 2 Quicksort A more efficient exchange sorting scheme than bubble sort – A typical exchange involves elements that are far apart.
Sorting – Lecture 3 More about Merge Sort, Quick Sort.
INTRO2CS Tirgul 8 1. Searching and Sorting  Tips for debugging  Binary search  Sorting algorithms:  Bogo sort  Bubble sort  Quick sort and maybe.
Algorithm Design Techniques, Greedy Method – Knapsack Problem, Job Sequencing, Divide and Conquer Method – Quick Sort, Finding Maximum and Minimum, Dynamic.
Bubble Sort Selection Sort Insertion Sort Merge Sort Quick Sort
Quicksort
Chapter 7 Sorting Spring 14
Data Structures and Algorithms
CSE 143 Lecture 23: quick sort.
Quicksort 1.
Welcome to CIS 068 ! Lesson 9: Sorting CIS 068.
Data Structures Review Session
slides adapted from Marty Stepp
Chapter 4.
Quicksort.
Quick-Sort 4/25/2019 8:10 AM Quick-Sort     2
Data Structures & Algorithms
Quicksort.
CSE 332: Sorting II Spring 2016.
Quicksort.
Presentation transcript:

C Programming Week 10 Sorting Algorithms 1

Sorting In many queries we handle a list of values and want a specific value. We can go through all the list until we find the requested value. But better… We can sort the list and then find it more easily (e.g., by binary search)

Sorting In class we saw several examples for sorting: –Bubble Sort –Merge Sort Today we will continue with examples… In these examples, each time we compare between two elements, resulting in a sorted list.

Quick Sort Divide and conquer –Divide the list into two sublists such that all elements from one list are greater than all elements from other list. –Sort each of these sublists recursively…

Quick Sort How we divide the list into two sublists? We pick up an element (pivot) and put all bigger elements to its right and all smaller elements to its left

Quick Sort At this stage, the pivot is in its final position

How do we choose the pivot? Ideally, we should take the median value However, it would take time to find what is the median, so we can take the: –First –Middle –Last –Any random element In practice, each such choice is relatively efficient.

Some visualization…

How do we implement this? First, we look on the ‘backbone’ of the algorithm: –Partitioning the list according to a pivot into two sublists. –After this stage, the pivot value is in its final position. –Recursively repeat this procedure to each of the two sublists.

Quick Sort (backbone) void quickSort (int list[], int start_index, int end_index) // This function implements the Quick Sort algorithm { int pivot_index; if (start_index<end_index) // more than one element in list { // We now partition the list into two sublists: pivot_index=partition(list, start_index, end_index); // Performing Quick Sort on both sublists: quickSort(list,start_index,pivot_index-1); quickSort(list,pivot_index+1,end_index); } 10 Where is the termination of the recursive function?

Partition 11 int partition (int list[], int start_index, int end_index) { int i,j; int pivot_index=choosePivot(start_index,end_index); int pivot_value=list[pivot_index]; swap(&list[start_index],&list[pivot_index]); i=start_index+1; j=end_index; while (i<=j) { while ((i<=end_index) &&(list[i]<=pivot_value)) i++; while ((j>=start_index) && (list[j]>pivot_value)) j--; if (i<j) swap(&list[i],&list[j]); } swap(&list[start_index],&list[j]); pivot_index=j; return pivot_index; }

main 12 int main() { int array[SIZE]={0}; int i; printf ("Please insert the numbers:\n"); for (i=0;i<SIZE;i++) { scanf ("%d",&array[i]); } printf ("The numbers before:\n"); printList(array,SIZE); quickSort (array,0,SIZE-1); printf ("The sorted numbers:\n"); printList(array,SIZE); return 0; }

Auxiliary Functions 13 int choosePivot(int start_index,int end_index) { return (end_index); } void swap(int *x, int *y) { int temp=*x; *x=*y; *y=temp; } void printList(int list[], int size) { int i; for (i=0;i<size;i++) { printf ("%d ",list[i]); } printf ("\n"); }

Sorting strings Similar to numbers we can sort strings according to their lexicographical order. What should we change for that? –Instead of comparing two numbers we should compare two strings according to their lexicographical order –Handling strings in input/printing etc.

Changing the comparison From (numbers): while (i<=j) { while ((i<=end_index) &&(list[i]<=pivot_value)) i++; while ((j>=start_index) && (list[j]>pivot_value)) j--; if (i<j) swap(&list[i],&list[j]); }

Changing the comparison To (strings): while (i<=j) { while ((i<=end_index) &&(strcmp(list[i],pivot_value)<=0)) i++; while ((j>=start_index) && (strcmp(list[j],pivot_value)>0)) j--; if (i<j) swap(list[i],list[j]); } Reminder: strcmp gets two strings and returns 0 if they are identical. Otherwise, it returns a negative or positive number if the first or second string appears first in lexicographical order, respectively. Now each element is a string, so we don’t need the ‘&’

The new Partition 17 int partition (char list[][SIZE], int start_index, int end_index) { int i,j; int pivot_index=choosePivot(start_index,end_index); char pivot_string[SIZE]=""; strcpy(pivot_string,list[pivot_index]); swap(list[start_index],list[pivot_index]); i=start_index+1; j=end_index; while (i<=j) { while ((i<=end_index) &&(strcmp(list[i],pivot_string)<=0)) i++; while ((j>=start_index) && (strcmp(list[j],pivot_string)>0)) j--; if (i<j) swap(list[i],list[j]); } swap(list[start_index],list[j]); pivot_index=j; return pivot_index; }

main 18 int main() { char list[NUM][SIZE]={""}; int i; printf ("Please insert the strings:\n"); for (i=0;i<NUM;i++) { readString(list[i],SIZE-1); } printf ("The strings before sorting:\n"); printList(list,NUM); quickSort (list,0,NUM-1); printf ("The sorted strings:\n"); printList(list,NUM); return 0; }

Auxiliary Functions 19 void readString(char string[],int size) { int i=0; char c; scanf("%c",&c); while ((c!='\n')&&(i<size)) { string[i]=c; i++; scanf("%c",&c); } string[i]='\0'; } void swap(char x[], char y[]) { int i=0; char temp[SIZE]=""; strcpy(temp,x); strcpy(x,y); strcpy(y,temp); }

Insertion Sort Another example for sorting algorithm is Insertion Sort: –In average, It is less efficient as compared to Quick Sort. –For small lists it is quicker as compared to other algorithms. –Many people perform similar algorithm when sorting elements (cards etc.) We will explain this algorithm in class while you will implement it in HW…

Insertion Sort The idea behind the algorithm: Go through the list from the first element and at each step put the i’th elements in its position in the sorted list that contain 1,…,i-1,i elements. At this stage, the first i elements are sorted. Stopping in i=n, we have a sorted list.

Example

Comparing Sorting… Quick Sort Insertion Sort

Complexity of algorithms We can compare the two algorithms in respect to time complexity. Here we shall introduce only the highlights of that complexity analysis.

Insertion Sort Best case scenario: –The list is already sorted. In this case, the i’th element is compared only to i-1 element. Thus, we have ~n comparisons. Worst case scenario: –The list is sorted backwards. In this case the i’th element needs to be shifted all the way back to the start of the list. –Quadratic complexity: n-1=~n 2 Average case (without proving): –It also takes ~n 2 operations.

Quick Sort The partition step takes ~n operations (we go through the list and change the location of the elements according to the pivot). Best case scenario: –In each partition, we divide the list into almost equal size lists (each containing (k-1)/2 elements). That means we have ~log(n) partitions. Therefore total time complexity is ~n*log(n).

Quick Sort Worst case scenario: –In each step we divide the list of k elements (starting from k=n) into k-1 and 1 elements. In this case each step takes ~n-k operations. Thus we have: (n-1)+(n-2)+(n-3)+…+1=~n 2.

Quick Sort Average case (without proving): –In this case it takes ~1.39n*log(n) operations. Thus, Quick Sort is faster than Insertion Sort on average. In fact, any algorithm for sorting n elements using pairwise comparisons cannot do it faster than ~n*log(n) in the average case.

Selection Sort Selection Sort is another sorting algorithm which is relatively simple: Given a list of elements: –Find the minimum and swap it with the first element. –Repeat it for the remainder of the list (now swapping with the 2 nd, 3 rd element etc.).

Selection Sort - Example

Complexity analysis In each step we look for the minimal element – thus we go through all the remaining elements. This is done n times. Time complexity is: (n)+(n-1)+(n-2)+…+1=~n 2 This is done on all inputs, therefore best case=worst case=average case.

And the winner is… Quick Sort Insertion Sort Selection Sort