Laboratorio di Algoritmi e Strutture Dati

Size: px
Start display at page:

Download "Laboratorio di Algoritmi e Strutture Dati"

Transcription

1 Laboratorio di Algoritmi e Strutture Dati Guido Fiorino guido.fiorino@unimib.it aa

2 Maximum in a sequence Given a sequence A 1,..., A N find the maximum. The maximum is in the first or in the second half of the sequence. If the sequence has one element we immediately have the answer. We can proceed recursively following a divide-and-conquer approach: Base case: if N = 1, then A 1 is the maximum; Recursion: 1 recursively compute the maximum of the sequence A 1,..., A N 2 ; 2 recursively compute the maximum of the sequence A N 2 +1,..., A N ; 3 the maximum of A 1,..., A N is the maximum between the two values. Exercise (method maximum) write a method int maximum(int[] a, int l, int r) that finds the maximum in the array a spanning from l to r.

3 3 Average of a sequence Given a sequence A 1,..., A N find the average. If we know the average of A 1,..., A N 2 and A N 2 +1,..., A N we can compute the average of the whole sequence by appropriately combining the two values. If the sequence has one element, then we immediately have the answer. We can proceed recursively following a divide-and-conquer approach: Base case: if N = 1, then A 1 is the average of the sequence; Recursion: 1 recursively compute the average of the sequence A 1,..., A N 2, let Av 1 be the value; 2 recursively compute the maximum of the sequence A N 2 +1,..., A N, let Av 2 be the value; 3 the average of A 1,..., A N is the Av 1 N 2 +Av 2 (N N 2 ) N Exercise (method avg) Write a method double avg(int[] a, int l, int r) that finds the average in the array a spanning from l to r.

4 4 Binary search Binary search is the alternative to the sequential search applicable to a sorted sequence A 1,..., A N, that is a sequence fulfilling the property: for every i = 1,..., N 1, A i A i+1 holds. Binary search can be described as a divide-and-conquer algorithm. Given a sorted sequence A 1,..., A N and X, proceed recursively as follows: Base case: if N = 0 (the given sequence is empty), then X is not in the sequence; Recursion: 1 if A N 2 = X, then X is in the sequence; 2 if A N 2 > X, then the answer is the result of recursively searching X in the sequence < A 1,..., A N 2 1, else the answer is the result of recursively searching X in the sequence < A N 2 +1,..., A N.

5 Binary search Exercise (method binsearch0) Write a Java method boolean binsearch0(int[] a, int X) that returns true if X occurs in the array a, false otherwise.

6 Binary search public static boolean binsearch0(int[] a, int X){ //empty sequence if (a.length == 0) return false; //X is found if (a[a.length/2] == X) return true; //search for X in the first middle if (a[a.length/2] > X){ int[] b = new int[a.length/2]; for(int i=0; i< b.length; i++) b[i]=a[i]; return binsearch0(b,x); else { //search for X in second middle int[] b = new int[a.length-a.length/2-1]; for(int i=0; i< b.length; i++) b[i]=a[i + a.length/2 + 1]; return binsearch0(b,x);

7 Binary search Exercise (method binsearch) Write a Java method boolean binsearch(int[] a, int X, int left, int right) that returns true if X occurs in the array a spanning from left to right, false otherwise.

8 Binary search //searches for X between a[left] to a[right] boolean binsearch(int[] a, int X, int left, int right){ //empty sequence if (left > right) return false; int middle = (left+right)/2; //X is found if (a[ middle ] == X) return true; //search for X in the first middle if (a[ middle ] > X) return binsearch(a, X, left, middle-1); else return binsearch(a, X, middle+1, right);

9 9 Searching in an unsorted sequence The searching in an unsorted sequence can be described by means of a divide-and-conquer approach. Given a sequence A 1,..., A N and X, proceed recursively as follows: Base case: if N = 0 (the given sequence is empty), then X is not in the sequence; Recursion: 1 if A N = X, then X is in the sequence; 2 2 proceed recursively, searching X in < A 1,..., A N 2 1. If X is found, then X is in the given sequence; 3 proceed recursively, searching X in < A N 2 +1,..., A N. If X is found, then X is in the given sequence. Exercise (method seqsearch) Write a Java method seqsearch that implements the divide-and-conquer approach to search a value in an unsorted sequence. The method seqsearch returns a boolean value. You are free to choose the formal parameters of seqsearch.

10 Palindromes A sequence A 1,..., A N that reads the same backward as forward is palindrome. This definition can be stated recursively as follows: a sequence A 1,..., A N is palindrome if A 1 = A N and A 2,..., A N 1 is palindrome. What about the base case? We have two base cases: the empty sequence and the sequence with one element. Definition (palindrome) A sequence A 1,..., A N is palindrome iff the sequence is empty (equivalently N = 0); the sequence contains one element (equivalently n = 1); A 1 = A n and the sequence A 2,..., A N 1 is palindrome.

11 Palindromes Exercise (method ispalindrome) Write a method boolean ispalindrome(char[] a, int l, int r) that returns true if the array a that spans between l and r is palindrome, false otherwise.

12 Reverse of an array The reverse of a sequence A 1,..., A N, denoted as rev( A 1,..., A N ), is the sequence A N,..., A 1. The definition emphasizes that function rev returns a particular permutation of a given sequence. Thus function rev maps sequences into sequences. Function rev has an easy recursive definition: { A1 if N = 1 rev( A 1,..., A N ) = rev( A 2,..., A n ), A 1 otherwise Exercise (method rev) Write a method int[] rev(int[]a,int i, int n) that returns the reverse of the array a that spans from i to n.

13 Filling a matrix Exercise (method fillmatrix) Use the divide-and-conquer approach to write a Java method fillmatrix that fills of binary digits a matrix M of 2 n rows and n columns, so that at M contains the binary representation of the first n integers. Example, with n = 3, M = You are free to decide the parameters and the returning value of fillmatrix. Possible signatures are int[][] fillmatrix(int c) that returns a matrix with 2 c rows and c columns void fillmatrix(int[][] M, int rmin, int rmax, int cmin, int cmax) that fills M spanning between the rows rmin and rmax and the columns cmin and cmax.

14 14 Maximum Contiguous Subsequence Sum Given a sequence containing (possibly negative) integers, A 1, A 2,..., A N, find the maximum value of j k=i A k. The maximum contiguous subsequence sum is zero if all the integers are negative. The problem can be solved by a divide-and-conquer algorithm. We divide the input in two halves: A 1,..., A N and A N +1,..., A N. 2 2 The maximum contiguous subsequence sum can occur: 1 entirely in the first half; 2 entirely in the second half; 3 begins in the first half but ends in the second half. Note that in this case the contiguous subsequence includes the last element of the first half and the first element of the second half. If we have the answers for each of the three possible cases we can provide the answer for the sequence A 1,..., A N comparing them and returning the greatest.

15 15 Maximum Contiguous Subsequence Sum Given the sequence A 1,..., A N, proceed recursively as follows: Base case: if N = 1 choose the largest between zero and A 1 ; Recursion: 1 recursively compute the maximum contiguous subsequence sum for contiguous subsequences entirely residing in the fist half; 2 recursively compute the maximum contiguous subsequence sum for contiguous subsequences entirely residing in the second half; 3 compute the maximum contiguous subsequence sum for contiguous subsequences that begins in the first half and ends in the second half; 4 the answer for A 1,..., A N is the maximum of the three values.

16 Maximum Contiguous Subsequence Sum To solve Point 3: 1 for each element in the first half, calculate the sum of the contiguous subsequence that ends at the rightmost item of the first half; 2 for each element in the second half, calculate the sum of the contiguous subsequence that starts at the leftmost item of the second half. The sum of maximum value found in each of previous points gives the maximum contiguous subsequence sum for a contiguous subsequence that spans between the two halves. Exercise (method mcss) Write a method int mcss(int[] a, int l, int r) that finds the maximum sum in the array a spanning from l to r by implementing the divide-and-conquer approach given above.

17 MergeSort Given a sequence A 1,..., A N, proceed recursively following the divide-and-conquer approach: Base case: if N = 1, then, the sequence is sorted, return A 1 ; Recursion: 1 recursively sort A 1,..., A N 2 ; 2 recursively sort A N 2 +1,..., A N ; 3 return the result of merging the two sorted subsequences obtained in the previous steps. The implementation of MergeSort depends on the implementation of Phase 3. There are different techniques to perform the merge. The aim is to save time.

18 MergeSort - Bitonic merge We are given an array A we copy A in an extra array E with the elements of the second sequence reversed E Then we merge in A starting from the leftmost cell: A 0 E A 0 2 E A E A E A E

19 MergeSort - Implementation of the bitonic merge //Bitonic merge. Ends with a[left..right] sorted static void merge(int[] a, int left, int m, int right){ int numberofcells = right-left+1, i, j; int[] extra = new int[numberofcells]; //copy a[left]..a[m] in extra[0]..extra[m-left] //in a future version we would like to save this copy for(i = left; i <= m ; i++){ extra[i-left] = a[i]; //copy a[right]..a[m+1] in extra[m+1-left]..extra[right-left] //note the reverse order for(j = right; j >= m+1; j--, i++) { extra[i-left] = a[j]; j = numberofcells-1; //index of last cell of extra i = 0; //index of first cell of extra for(int k = 0; k < numberofcells; k++){ if(extra[i]>extra[j]) { a[k+left]=extra[j--]; else { a[k+left] = extra[i++]; //end bitonicmerge

20 Bitonic merge - exercises Exercise (Variants of the bitonic merge) The code can be changed along this lines public class MergeSort{ //better solution: use extra as member of the class private static int[] extra; public static void sort(int[] a){ extra = new int[a.length]; sort(a, 0, a.length-1); //This method sorts a[left..right] static private void sort(int[] a, int left, int right){ /* write the recursive code for the mergesort */ // end merge // bitonic merge static void merge(int[] a, int left, int m, int right){ /* write here the new code for the bitonic merge */ //end bitonic merge //end class MergeSort

21 MergeSort - merge of two sources in a destination public class MergeSort{ private static int[] extra; /* merge s1[s1left..s1right] and s2[s2left..s2right] into dest starting from cell of index destleft */ static void merge(int[] dest, int destleft, int[] s1, int s1left, int s1right, int[] s2, int s2left, int s2right ) { int q = (s1right-s1left+1) + (s2right-s2left+1); //data to copy int destright = destleft + q -1; //index of the last data for(int i = destleft; i <= destright ; i++){ if (s1left>s1right){ // all data in s1 have been already copied in dest dest[i] = s2[s2left++]; else if (s2left>s2right){ // all data in s2 have been already copied in dest dest[i] = s1[s1left++]; else if (s1[ s1left ] < s2 [ s2left ]){ dest[i] = s1[ s1left++ ]; else dest[i] = s2[ s2left++ ]; //end merge Class continues in the next slide... 21

22 MergeSort - merge two sources in a destination public static void sort(int[] a){ extra = new int[a.length]; for(int i=0; i<a.length; i++) { extra[i] = a[i]; //Important: copy a in extra. Why? //sort the data in extra[0..a.length-1] and //put the result in array a sort(a, extra, 0, a.length-1); //now array a is sorted See next slide...

23 MergeSort - exchanging roles of source and destination //sort data in source and put the result in dest static private void sort(int[] dest, int[] source, int left, int right) { if (right - left > 0){ //the sequence has at least one element int m=(left + right)/2; //sort dest[left..m] and put the result in source[left..m] //note the exchange between source and dest! sort(source, dest, left, m); //sort dest[m+1..right] and put the result in source[m+1..right]; sort(source, dest, m+1, right); //merge source[left..m] and source[m+1..right] and put the result in //dest, starting from left, in practice the result goes in dest[left..right] merge(dest, left, source, left, m, source, m+1, right); //end if, note that the base case is implicit // end sort //end class

24 MergeSort - the copy of the source data in extra Exercise (Question) Can you explain why we have this code? for(int i=0; i<a.length; i++) { extra[i] = a[i]; //Important: copy a in extra. Why? Compare the previous version of MergeSort with the following one and remember that our aim is to save to copy data between extra and a as much as possible.

25 MergeSort - saving the copy public class MergeSort{ private static int[] extra; /* the role of the array a and the extra array as source of the data and destination of the merging is continuously exchanged; in this way we save the copy from a to extra that is performed in the bitonic merge */ public static void sort(int[] a){ extra = new int[a.length]; /* sort the data in extra[0..a.length-1] and put the result in a; */ sort(a, extra, 0, a.length-1); //end sort Class MergeSort continues in the next slide

26 MergeSort - saving the copy //sort data in source[left..right] and put the result in dest[left..right] static void sort(int[] dest, int[] source, int left, int right) { if (right-left == 0){ /* Note that we have an explicit base case. Compare with the previous version */ if (dest == extra) { /* dest == extra true means that source contains the data and the assignment is required. Note that this check is not present in the previous version. */ dest[right]=source[right]; return ; /* end base case */ Method static void sort(int[] dest, int[] source, int left, int right) continues in the next slide

27 MergeSort - saving the copy //recursive part //the sequence has at least one element int m=(left + right)/2; //sort dest[left..m] and put the result in source[left..m] sort(source, dest, left, m); //sort dest[m+1..right] and put the result in source[m+1..right]; sort(source, dest, m+1, right); //merge source[left..m] and source[m+1..right] and put the result in //dest, starting from left, in practice the result goes in dest[left..right] merge(dest, left, source, left, m, source, m+1, right); // end sort static void merge(int[] dest, int destleft, int[] s1, int s1left, int s1right, int[] s2, int s2left, int s2right ) { /* see the code given in a previous slide */ // end class MergeSort

28 28 Listing all permutations of a sequence There are N! permutations of a given a sequence A 1,..., A N, where all the elements are distinct, that is for every A i, A j of the sequence, A i A j if i j. We can describe the set of all permutations of A 1,..., A N by a recursive definition that follows a divide-and-conquer approach: Base case: if N = 1, then A 1 is the only permutation; Recursion: 1 For i = 1,..., N, recursively compute the set S i of permutations of the sequence A 1,..., A i 1, A i+1,... A N ; let V i the set obtained by inserting A i as first element of every sequence in S i, that is V i = { A i, B 1,... B N 1 B 1,... B N 1 S i ; 2 V = V 1 V N is the set of all permutations of A 1,..., A N.

29 Listing all permutations of a sequence Exercise Use the description given in the previous page to write a Java method int[][] listperms(int[] seq) returning a matrix containing the list of the permutations of seq. If you need, method listperms can have more than one formal parameter.

30 30 Listing all permutations of a sequence An alternative is: Base case: if N = 1, then A 1 is the only permutation; Recursion: 1 recursively compute the set S of permutations of the sequence A 2,... A N ; 2 for every sequence B 1,..., B N 1 in S, build the N new subsequences A 1, B 1,..., B N 1, B 1, A 1, B 2,..., B N 1,. B 1,..., B N 1, A 1. This is the set V of the permutations of A 1,..., A N, that is: V = { B 1,..., B j 1, A 1, B j,..., B N 1 B 1,..., B j 1, B j,..., B N 1 S and for j = 1,..., N 1

31 Listing all permutations of a sequence Exercise Use the description given in the previous page to write a Java method int[][] listpermstwo(int[] seq) returning a matrix containing the list of the permutations of seq. If you need, method listpermstwo can have more than one formal parameter.

32 Listing all permutations of a sequence A further alternative to describe the listing of the permutations of a sequence A 1,..., A N is by introducing a second sequence that we call the prefix. The following description is parametrized on two sequences of elements that we call Seq and Prefix. To obtain the list of the permutations of A 1,..., A N, we set Seq = A 1,..., A N and Prefix =. To make the description clearer, we emphasizes the formal parameters of the procedure:

33 33 Listing all permutations of a sequence ListPerm(Seq, Prefix) Base case: if Seq contains one element, then the sequence obtained by the elements in Prefix followed by the element in Seq is a permutation A 1,..., A N in the first call; Recursion: 1 For every element A in Seq Let Seq be the result of erasing from Seq the element A; Let Prefix = A, B 1,..., B u where B 1,..., B u is the sequence in Prefix; ListPerm(Seq, Prefix ), in other words, proceed recursively on Seq, Prefix. In the following, the method listperm provides a Java implementation of the procedure.

34 Listing all permutations of a sequence public static void listperm(int[] a, int[] prefix) { // base case if (a.length == 1) { System.out.print(a[0] + "; "); for (int i = 0; i < prefix.length; i++) { System.out.print(prefix[i] + "; "); System.out.println(); return; The method listperm(int[] a, int[] prefix) continues in the next slide...

35 Listing all permutations of a sequence // recursive step int[] seq1 = new int[a.length - 1]; //this is seq int[] prefix1 = new int[prefix.length + 1]; //this is prefix //build prefix : copy prefix in prefix for(int i = 1; i < prefix1.length; i++) { prefix1[i] = prefix[i-1]; for(int j = a.length - 1; j >= 0; j--) { //complete prefix : put an element of a as first element of prefix prefix1[0] = a[j]; //build seq for(int i = 0, k = 0; i < a.length; i++) { if (i!= j) { seq1[k] = a[i]; k++; perms(seq1, prefix1); //end listperm

36 36 Listing all permutations of a sequence Remark Our implementation strictly follows the description. A better implementation could be provided, possibly using some more formal parameters.

37 37 A collection of exercises on divide-and-conquer method 1 Use the technique divide-and-conquer to write a Java method int count10(int[] a, int left, int right) that returns the frequency of the sequence 1, 0 in the array a spanning from left to right; 2 use the technique divide-and-conquer to write a Java method int findbba(char[] a, int left, int right) that returns the frequency of the string BBA in the array a spanning from left to right; 3 use the technique divide-and-conquer, write a Java method int countooe(int[] a, int left, int right) that returns the number of times that in the array a spanning from left to right an even number is immediately preceded by two odd numbers; 4 use the technique divide-and-conquer, write a Java method int counttruetrue(boolean[] a, int left, int right) that returns the frequency of true, true in the array a spanning from left to right; 5 use the technique divide-and-conquer, write a Java method boolean evenvowels(char[] a, int left, int right) that returns true if in the array a spanning from left to right the number of vowels is even, false otherwise; 6 use the technique divide-and-conquer to write a Java method int count1001(int[] a, int left, int right) that returns the frequency of the sequence 1, 0, 0, 1 in the array a spanning from left to right.

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University CS 112 Introduction to Computing II Wayne Snyder Department Boston University Today Recursive Sorting Methods and their Complexity: Mergesort Conclusions on sorting algorithms and complexity Next Time:

More information

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University 0/6/6 CS Introduction to Computing II Wayne Snyder Department Boston University Today Conclusions on Iterative Sorting: Complexity of Insertion Sort Recursive Sorting Methods and their Complexity: Mergesort

More information

Scan and its Uses. 1 Scan. 1.1 Contraction CSE341T/CSE549T 09/17/2014. Lecture 8

Scan and its Uses. 1 Scan. 1.1 Contraction CSE341T/CSE549T 09/17/2014. Lecture 8 CSE341T/CSE549T 09/17/2014 Lecture 8 Scan and its Uses 1 Scan Today, we start by learning a very useful primitive. First, lets start by thinking about what other primitives we have learned so far? The

More information

CS 310 Advanced Data Structures and Algorithms

CS 310 Advanced Data Structures and Algorithms CS 310 Advanced Data Structures and Algorithms Sorting June 13, 2017 Tong Wang UMass Boston CS 310 June 13, 2017 1 / 42 Sorting One of the most fundamental problems in CS Input: a series of elements with

More information

ESc101 : Fundamental of Computing

ESc101 : Fundamental of Computing ESc101 : Fundamental of Computing I Semester 2008-09 Lecture 37 Analyzing the efficiency of algorithms. Algorithms compared Sequential Search and Binary search GCD fast and GCD slow Merge Sort and Selection

More information

Lecture 2: Getting Started

Lecture 2: Getting Started Lecture 2: Getting Started Insertion Sort Our first algorithm is Insertion Sort Solves the sorting problem Input: A sequence of n numbers a 1, a 2,..., a n. Output: A permutation (reordering) a 1, a 2,...,

More information

4.2 Sorting and Searching. Section 4.2

4.2 Sorting and Searching. Section 4.2 4.2 Sorting and Searching 1 Sequential Search Scan through array, looking for key. Search hit: return array index. Search miss: return -1. public static int search(string key, String[] a) { int N = a.length;

More information

Lecture 7 Quicksort : Principles of Imperative Computation (Spring 2018) Frank Pfenning

Lecture 7 Quicksort : Principles of Imperative Computation (Spring 2018) Frank Pfenning Lecture 7 Quicksort 15-122: Principles of Imperative Computation (Spring 2018) Frank Pfenning In this lecture we consider two related algorithms for sorting that achieve a much better running time than

More information

Lecture Notes on Quicksort

Lecture Notes on Quicksort Lecture Notes on Quicksort 15-122: Principles of Imperative Computation Frank Pfenning Lecture 8 February 5, 2015 1 Introduction In this lecture we consider two related algorithms for sorting that achieve

More information

Better sorting algorithms (Weiss chapter )

Better sorting algorithms (Weiss chapter ) Better sorting algorithms (Weiss chapter 8.5 8.6) Divide and conquer Very general name for a type of recursive algorithm You have a problem to solve. Split that problem into smaller subproblems Recursively

More information

UNIT 7. SEARCH, SORT AND MERGE

UNIT 7. SEARCH, SORT AND MERGE UNIT 7. SEARCH, SORT AND MERGE ALGORITHMS Year 2017-2018 Industrial Technology Engineering Paula de Toledo CONTENTS 7.1. SEARCH 7.2. SORT 7.3. MERGE 2 SEARCH Search, sort and merge algorithms Search (search

More information

8/5/10 TODAY'S OUTLINE. Recursion COMP 10 EXPLORING COMPUTER SCIENCE. Revisit search and sorting using recursion. Recursion WHAT DOES THIS CODE DO?

8/5/10 TODAY'S OUTLINE. Recursion COMP 10 EXPLORING COMPUTER SCIENCE. Revisit search and sorting using recursion. Recursion WHAT DOES THIS CODE DO? 8/5/10 TODAY'S OUTLINE Recursion COMP 10 EXPLORING COMPUTER SCIENCE Revisit search and sorting using recursion Binary search Merge sort Lecture 8 Recursion WHAT DOES THIS CODE DO? A function is recursive

More information

Mergesort again. 1. Split the list into two equal parts

Mergesort again. 1. Split the list into two equal parts Quicksort Mergesort again 1. Split the list into two equal parts 5 3 9 2 8 7 3 2 1 4 5 3 9 2 8 7 3 2 1 4 Mergesort again 2. Recursively mergesort the two parts 5 3 9 2 8 7 3 2 1 4 2 3 5 8 9 1 2 3 4 7 Mergesort

More information

ESC101 : Fundamental of Computing

ESC101 : Fundamental of Computing ESC101 : Fundamental of Computing End Semester Exam 19 November 2008 Name : Roll No. : Section : Note : Read the instructions carefully 1. You will lose 3 marks if you forget to write your name, roll number,

More information

Sorting. There exist sorting algorithms which have shown to be more efficient in practice.

Sorting. There exist sorting algorithms which have shown to be more efficient in practice. Sorting Next to storing and retrieving data, sorting of data is one of the more common algorithmic tasks, with many different ways to perform it. Whenever we perform a web search and/or view statistics

More information

Sorting L7.2 Recall linear search for an element in an array, which is O(n). The divide-and-conquer technique of binary search divides the array in ha

Sorting L7.2 Recall linear search for an element in an array, which is O(n). The divide-and-conquer technique of binary search divides the array in ha Lecture Notes on Sorting 15-122: Principles of Imperative Computation Frank Pfenning Lecture 7 February 1, 2011 1 Introduction We have seen in the last lecture that sorted arrays drastically reduce the

More information

Analysis of Algorithms. Unit 4 - Analysis of well known Algorithms

Analysis of Algorithms. Unit 4 - Analysis of well known Algorithms Analysis of Algorithms Unit 4 - Analysis of well known Algorithms 1 Analysis of well known Algorithms Brute Force Algorithms Greedy Algorithms Divide and Conquer Algorithms Decrease and Conquer Algorithms

More information

2. Each element of an array is accessed by a number known as a(n) a. a. subscript b. size declarator c. address d. specifier

2. Each element of an array is accessed by a number known as a(n) a. a. subscript b. size declarator c. address d. specifier Lesson 4 Arrays and Lists Review CSC 123 Fall 2018 Answer Sheet Short Answers 1. In an array declaration, this indicates the number of elements that the array will have. b a. subscript b. size declarator

More information

Sorting. Task Description. Selection Sort. Should we worry about speed?

Sorting. Task Description. Selection Sort. Should we worry about speed? Sorting Should we worry about speed? Task Description We have an array of n values in any order We need to have the array sorted in ascending or descending order of values 2 Selection Sort Select the smallest

More information

Recursion: Factorial (1) Recursion. Recursion: Principle. Recursion: Factorial (2) Recall the formal definition of calculating the n factorial:

Recursion: Factorial (1) Recursion. Recursion: Principle. Recursion: Factorial (2) Recall the formal definition of calculating the n factorial: Recursion EECS2030: Advanced Object Oriented Programming Fall 2017 CHEN-WEI WANG Recursion: Factorial (1) Recall the formal definition of calculating the n factorial: 1 if n = 0 n! = n (n 1) (n 2) 3 2

More information

Recursion. Tracing Method Calls via a Stack. Beyond this lecture...

Recursion. Tracing Method Calls via a Stack. Beyond this lecture... Recursion EECS2030 B: Advanced Object Oriented Programming Fall 2018 CHEN-WEI WANG Recursion: Principle Recursion is useful in expressing solutions to problems that can be recursively defined: Base Cases:

More information

3/19/2015. Chapter 19 Sorting and Searching SELECTION SORT PROFILING THE SELECTION SORT ALGORITHM SELECTION SORT ON VARIOUS SIZE ARRAYS*

3/19/2015. Chapter 19 Sorting and Searching SELECTION SORT PROFILING THE SELECTION SORT ALGORITHM SELECTION SORT ON VARIOUS SIZE ARRAYS* Chapter 19 Sorting and Searching The Plan For Today AP Test Last Call Chapter 18 Quiz Corrections Chapter 18 Assignment Towers of Hanoi Chapter 19 19.4: Merge Sort 19.5: Analyzing the Merge Sort Algorithm

More information

Homework Assignment #3. 1 (5 pts) Demonstrate how mergesort works when sorting the following list of numbers:

Homework Assignment #3. 1 (5 pts) Demonstrate how mergesort works when sorting the following list of numbers: CISC 4080 Computer Algorithms Spring, 2019 Homework Assignment #3 1 (5 pts) Demonstrate how mergesort works when sorting the following list of numbers: 6 1 4 2 3 8 7 5 2 Given the following array (list),

More information

4. Sorting and Order-Statistics

4. Sorting and Order-Statistics 4. Sorting and Order-Statistics 4. Sorting and Order-Statistics The sorting problem consists in the following : Input : a sequence of n elements (a 1, a 2,..., a n ). Output : a permutation (a 1, a 2,...,

More information

Cosc 241 Programming and Problem Solving Lecture 17 (30/4/18) Quicksort

Cosc 241 Programming and Problem Solving Lecture 17 (30/4/18) Quicksort 1 Cosc 241 Programming and Problem Solving Lecture 17 (30/4/18) Quicksort Michael Albert michael.albert@cs.otago.ac.nz Keywords: sorting, quicksort The limits of sorting performance Algorithms which sort

More information

DO NOT. UNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division. P. N.

DO NOT. UNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division. P. N. CS61B Fall 2011 UNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division Test #2 Solutions P. N. Hilfinger 1. [3 points] Consider insertion sort, merge

More information

Sorting and Searching Algorithms

Sorting and Searching Algorithms Sorting and Searching Algorithms Tessema M. Mengistu Department of Computer Science Southern Illinois University Carbondale tessema.mengistu@siu.edu Room - Faner 3131 1 Outline Introduction to Sorting

More information

Mergesort again. 1. Split the list into two equal parts

Mergesort again. 1. Split the list into two equal parts Quicksort Mergesort again 1. Split the list into two equal parts 5 3 9 2 8 7 3 2 1 4 5 3 9 2 8 7 3 2 1 4 Mergesort again 2. Recursively mergesort the two parts 5 3 9 2 8 7 3 2 1 4 2 3 5 8 9 1 2 3 4 7 Mergesort

More information

Recursion. EECS2030: Advanced Object Oriented Programming Fall 2017 CHEN-WEI WANG

Recursion. EECS2030: Advanced Object Oriented Programming Fall 2017 CHEN-WEI WANG Recursion EECS2030: Advanced Object Oriented Programming Fall 2017 CHEN-WEI WANG Recursion: Principle Recursion is useful in expressing solutions to problems that can be recursively defined: Base Cases:

More information

Scan and Quicksort. 1 Scan. 1.1 Contraction CSE341T 09/20/2017. Lecture 7

Scan and Quicksort. 1 Scan. 1.1 Contraction CSE341T 09/20/2017. Lecture 7 CSE341T 09/20/2017 Lecture 7 Scan and Quicksort 1 Scan Scan is a very useful primitive for parallel programming. We will use it all the time in this class. First, lets start by thinking about what other

More information

Divide and Conquer Algorithms

Divide and Conquer Algorithms CSE341T 09/13/2017 Lecture 5 Divide and Conquer Algorithms We have already seen a couple of divide and conquer algorithms in this lecture. The reduce algorithm and the algorithm to copy elements of the

More information

CSCE 110 Dr. Amr Goneid Exercise Sheet (7): Exercises on Recursion (Solutions)

CSCE 110 Dr. Amr Goneid Exercise Sheet (7): Exercises on Recursion (Solutions) CSCE 110 Dr. Amr Goneid Exercise Sheet (7): Exercises on Recursion (Solutions) Consider the following recursive function: int what ( int x, int y) if (x > y) return what (x-y, y); else if (y > x) return

More information

UNIT-2. Problem of size n. Sub-problem 1 size n/2. Sub-problem 2 size n/2. Solution to the original problem

UNIT-2. Problem of size n. Sub-problem 1 size n/2. Sub-problem 2 size n/2. Solution to the original problem Divide-and-conquer method: Divide-and-conquer is probably the best known general algorithm design technique. The principle behind the Divide-and-conquer algorithm design technique is that it is easier

More information

Lecture Notes on Quicksort

Lecture Notes on Quicksort Lecture Notes on Quicksort 15-122: Principles of Imperative Computation Frank Pfenning Lecture 8 September 20, 2012 1 Introduction In this lecture we first sketch two related algorithms for sorting that

More information

McGill University Faculty of Science School of Computer Science. MIDTERM EXAMINATION - Sample solutions. COMP-250: Introduction to Computer Science

McGill University Faculty of Science School of Computer Science. MIDTERM EXAMINATION - Sample solutions. COMP-250: Introduction to Computer Science STUDENT NAME: STUDENT ID: McGill University Faculty of Science School of Computer Science MIDTERM EXAMINATION - Sample solutions COMP-250: Introduction to Computer Science March 12, 2014 Examiner: Prof.

More information

Quick-Sort. Quick-sort is a randomized sorting algorithm based on the divide-and-conquer paradigm:

Quick-Sort. Quick-sort is a randomized sorting algorithm based on the divide-and-conquer paradigm: Presentation for use with the textbook Data Structures and Algorithms in Java, 6 th edition, by M. T. Goodrich, R. Tamassia, and M. H. Goldwasser, Wiley, 2014 Quick-Sort 7 4 9 6 2 2 4 6 7 9 4 2 2 4 7 9

More information

COMP Data Structures

COMP Data Structures COMP 2140 - Data Structures Shahin Kamali Topic 5 - Sorting University of Manitoba Based on notes by S. Durocher. COMP 2140 - Data Structures 1 / 55 Overview Review: Insertion Sort Merge Sort Quicksort

More information

Divide and Conquer Sorting Algorithms and Noncomparison-based

Divide and Conquer Sorting Algorithms and Noncomparison-based Divide and Conquer Sorting Algorithms and Noncomparison-based Sorting Algorithms COMP1927 16x1 Sedgewick Chapters 7 and 8 Sedgewick Chapter 6.10, Chapter 10 DIVIDE AND CONQUER SORTING ALGORITHMS Step 1

More information

Parallel Sorting Algorithms

Parallel Sorting Algorithms CSC 391/691: GPU Programming Fall 015 Parallel Sorting Algorithms Copyright 015 Samuel S. Cho Sorting Algorithms Review Bubble Sort: O(n ) Insertion Sort: O(n ) Quick Sort: O(n log n) Heap Sort: O(n log

More information

All answers will be posted on web site, and most will be reviewed in class.

All answers will be posted on web site, and most will be reviewed in class. Lesson 4 Arrays and Lists Review CSC 123 Fall 2018 Notes: All homework must be submitted via e-mail. All parts of assignment must be submitted in a single e-mail with multiple attachments when required.

More information

Data Structures COE 312 ExamII Preparation Exercises

Data Structures COE 312 ExamII Preparation Exercises Data Structures COE 312 ExamII Preparation Exercises 1. Patrick designed an algorithm called search2d that can be used to find a target element x in a two dimensional array A of size N = n 2. The algorithm

More information

Searching and Sorting (Savitch, Chapter 7.4)

Searching and Sorting (Savitch, Chapter 7.4) Searching and Sorting (Savitch, Chapter 7.4) TOPICS Algorithms Complexity Binary Search Bubble Sort Insertion Sort Selection Sort What is an algorithm? A finite set of precise instruc6ons for performing

More information

DO NOT. UNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division. P. N.

DO NOT. UNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division. P. N. CS61B Fall 2013 UNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division Test #2 Solutions DO NOT P. N. Hilfinger REPRODUCE 1 Test #2 Solution 2 Problems

More information

CHAPTER 7 Iris Hui-Ru Jiang Fall 2008

CHAPTER 7 Iris Hui-Ru Jiang Fall 2008 CHAPTER 7 SORTING Iris Hui-Ru Jiang Fall 2008 2 Contents Comparison sort Bubble sort Selection sort Insertion sort Merge sort Quick sort Heap sort Introspective sort (Introsort) Readings Chapter 7 The

More information

APCS Semester #1 Final Exam Practice Problems

APCS Semester #1 Final Exam Practice Problems Name: Date: Per: AP Computer Science, Mr. Ferraro APCS Semester #1 Final Exam Practice Problems The problems here are to get you thinking about topics we ve visited thus far in preparation for the semester

More information

Sorting. Weiss chapter , 8.6

Sorting. Weiss chapter , 8.6 Sorting Weiss chapter 8.1 8.3, 8.6 Sorting 5 3 9 2 8 7 3 2 1 4 1 2 2 3 3 4 5 7 8 9 Very many different sorting algorithms (bubblesort, insertion sort, selection sort, quicksort, heapsort, mergesort, shell

More information

What is an algorithm?

What is an algorithm? /0/ What is an algorithm? Searching and Sorting (Savitch, Chapter 7.) TOPICS Algorithms Complexity Binary Search Bubble Sort Insertion Sort Selection Sort A finite set of precise instrucons for performing

More information

NATIONAL UNIVERSITY OF SINGAPORE

NATIONAL UNIVERSITY OF SINGAPORE NATIONAL UNIVERSITY OF SINGAPORE SCHOOL OF COMPUTING EXAMINATION FOR CS1020 Semester 2: AY2011/12 CS1020 Data Structures and Algorithms I April 2012 Time allowed: 2 hours Matriculation number: INSTRUCTIONS

More information

Solutions Manual. Data Structures and Algorithms in Java, 5th edition International Student Version. M. T. Goodrich and R.

Solutions Manual. Data Structures and Algorithms in Java, 5th edition International Student Version. M. T. Goodrich and R. Solutions Manual Data Structures and Algorithms in Java, 5th edition International Student Version M. T. Goodrich and R. Tamassia Chapter 1 Reinforcement Solution R-1.1 Since, after the clone, A[4] and

More information

Sorting Algorithms. + Analysis of the Sorting Algorithms

Sorting Algorithms. + Analysis of the Sorting Algorithms Sorting Algorithms + Analysis of the Sorting Algorithms Insertion Sort What if first k elements of array are already sorted? 4, 7, 12, 5, 19, 16 We can shift the tail of the sorted elements list down and

More information

Data Structures and Algorithms for Engineers

Data Structures and Algorithms for Engineers 0-630 Data Structures and Algorithms for Engineers David Vernon Carnegie Mellon University Africa vernon@cmu.edu www.vernon.eu Data Structures and Algorithms for Engineers 1 Carnegie Mellon University

More information

Building Java Programs Chapter 13

Building Java Programs Chapter 13 Building Java Programs Chapter 13 Searching and Sorting Copyright (c) Pearson 2013. All rights reserved. Sequential search sequential search: Locates a target value in an array/list by examining each element

More information

It is a constructor and is called using the new statement, for example, MyStuff m = new MyStuff();

It is a constructor and is called using the new statement, for example, MyStuff m = new MyStuff(); COSC 117 Exam 3 Key Fall 2012 Part 1: Definitions & Short Answer (3 Points Each) 1. A method in a class that has no return type and the same name as the class is called what? How is this type of method

More information

Lecture 6 Sequences II. Parallel and Sequential Data Structures and Algorithms, (Fall 2013) Lectured by Danny Sleator 12 September 2013

Lecture 6 Sequences II. Parallel and Sequential Data Structures and Algorithms, (Fall 2013) Lectured by Danny Sleator 12 September 2013 Lecture 6 Sequences II Parallel and Sequential Data Structures and Algorithms, 15-210 (Fall 2013) Lectured by Danny Sleator 12 September 2013 Material in this lecture: Today s lecture is about reduction.

More information

Public-Service Announcement

Public-Service Announcement Public-Service Announcement Computer Science Mentors (CSM) will be running small group sections this semester! CSM is a student organization that aims to create a stronger feeling of community in classes

More information

CS61B Lecture #6: Arrays

CS61B Lecture #6: Arrays CS61B Lecture #6: Arrays Readings for Monday : Chapters 2, 4 of Head First Java (5 also useful, but its really review). Upcoming readings : Chapters 7, 8 of Head First Java. Public Service Announcement.

More information

Data Structures Brett Bernstein

Data Structures Brett Bernstein Data Structures Brett Bernstein Lecture Review Exercises. Given sorted lists, return the number of elements they have in common. public static int numshared(int[] a, int[] b). Given sorted lists, return

More information

Sorting. Popular algorithms: Many algorithms for sorting in parallel also exist.

Sorting. Popular algorithms: Many algorithms for sorting in parallel also exist. Sorting Popular algorithms: Selection sort* Insertion sort* Bubble sort* Quick sort* Comb-sort Shell-sort Heap sort* Merge sort* Counting-sort Radix-sort Bucket-sort Tim-sort Many algorithms for sorting

More information

Searching in General

Searching in General Searching in General Searching 1. using linear search on arrays, lists or files 2. using binary search trees 3. using a hash table 4. using binary search in sorted arrays (interval halving method). Data

More information

4/27/2012. Chapter Fourteen: Sorting and Searching. Chapter Goals

4/27/2012. Chapter Fourteen: Sorting and Searching. Chapter Goals Chapter Fourteen: Sorting and Searching Chapter Goals To study several sorting and searching algorithms To appreciate that algorithms for the same task can differ widely in performance To understand the

More information

Fundamental problem in computing science. putting a collection of items in order. Often used as part of another algorithm

Fundamental problem in computing science. putting a collection of items in order. Often used as part of another algorithm cmpt-225 Sorting Sorting Fundamental problem in computing science putting a collection of items in order Often used as part of another algorithm e.g. sort a list, then do many binary searches e.g. looking

More information

Quicksort (Weiss chapter 8.6)

Quicksort (Weiss chapter 8.6) Quicksort (Weiss chapter 8.6) Recap of before Easter We saw a load of sorting algorithms, including mergesort To mergesort a list: Split the list into two halves Recursively mergesort the two halves Merge

More information

CS1020 Data Structures and Algorithms I Lecture Note #14. Sorting

CS1020 Data Structures and Algorithms I Lecture Note #14. Sorting CS1020 Data Structures and Algorithms I Lecture Note #14 Sorting Objectives 1 2 To learn some classic sorting algorithms To analyse the running time of these algorithms 3 To learn concepts such as in-place

More information

CS 137 Part 8. Merge Sort, Quick Sort, Binary Search. November 20th, 2017

CS 137 Part 8. Merge Sort, Quick Sort, Binary Search. November 20th, 2017 CS 137 Part 8 Merge Sort, Quick Sort, Binary Search November 20th, 2017 This Week We re going to see two more complicated sorting algorithms that will be our first introduction to O(n log n) sorting algorithms.

More information

Name: UTLN: CS login: Comp 15 Data Structures Midterm 2018 Summer

Name: UTLN: CS login: Comp 15 Data Structures Midterm 2018 Summer [Closed book exam] There are 7 questions leading up to 100 points. Max alloted time: 1 hour Problem 1 (2x10=20 points). Fill in the blanks in terms of the big-theta (Θ) notation to show the asymptotic

More information

CSCE 110 Dr. Amr Goneid Exercise Sheet (7): Exercises on Recursion

CSCE 110 Dr. Amr Goneid Exercise Sheet (7): Exercises on Recursion CSCE 110 Dr. Amr Goneid Exercise Sheet (7): Exercises on Recursion Consider the following recursive function: int what ( int x, int y) if (x > y) return what (x-y, y); else if (y > x) return what (x, y-x);

More information

Unit 10: Sorting/Searching/Recursion

Unit 10: Sorting/Searching/Recursion Unit 10: Sorting/Searching/Recursion Notes AP CS A Searching. Here are two typical algorithms for searching a collection of items (which for us means an array or a list). A Linear Search starts at the

More information

Problem. Input: An array A = (A[1],..., A[n]) with length n. Output: a permutation A of A, that is sorted: A [i] A [j] for all. 1 i j n.

Problem. Input: An array A = (A[1],..., A[n]) with length n. Output: a permutation A of A, that is sorted: A [i] A [j] for all. 1 i j n. Problem 5. Sorting Simple Sorting, Quicksort, Mergesort Input: An array A = (A[1],..., A[n]) with length n. Output: a permutation A of A, that is sorted: A [i] A [j] for all 1 i j n. 98 99 Selection Sort

More information

Divide-and-Conquer. Dr. Yingwu Zhu

Divide-and-Conquer. Dr. Yingwu Zhu Divide-and-Conquer Dr. Yingwu Zhu Divide-and-Conquer The most-well known algorithm design technique: 1. Divide instance of problem into two or more smaller instances 2. Solve smaller instances independently

More information

Sorting. Bringing Order to the World

Sorting. Bringing Order to the World Lecture 10 Sorting Bringing Order to the World Lecture Outline Iterative sorting algorithms (comparison based) Selection Sort Bubble Sort Insertion Sort Recursive sorting algorithms (comparison based)

More information

DIVIDE AND CONQUER ALGORITHMS ANALYSIS WITH RECURRENCE EQUATIONS

DIVIDE AND CONQUER ALGORITHMS ANALYSIS WITH RECURRENCE EQUATIONS CHAPTER 11 SORTING ACKNOWLEDGEMENT: THESE SLIDES ARE ADAPTED FROM SLIDES PROVIDED WITH DATA STRUCTURES AND ALGORITHMS IN C++, GOODRICH, TAMASSIA AND MOUNT (WILEY 2004) AND SLIDES FROM NANCY M. AMATO AND

More information

Sorting. Bubble Sort. Selection Sort

Sorting. Bubble Sort. Selection Sort Sorting In this class we will consider three sorting algorithms, that is, algorithms that will take as input an array of items, and then rearrange (sort) those items in increasing order within the array.

More information

CSE 143 Lecture 22. Sorting. reading: 13.1, slides adapted from Marty Stepp and Hélène Martin

CSE 143 Lecture 22. Sorting. reading: 13.1, slides adapted from Marty Stepp and Hélène Martin CSE 143 Lecture 22 Sorting reading: 13.1, 13.3-13.4 slides adapted from Marty Stepp and Hélène Martin http://www.cs.washington.edu/143/ Sorting sorting: Rearranging the values in an array or collection

More information

University of Palestine. Mid Exam Total Grade: 100

University of Palestine. Mid Exam Total Grade: 100 First Question No. of Branches (5) A) Choose the correct answer: 1. If we type: system.out.println( a ); in the main() method, what will be the result? int a=12; //in the global space... void f() { int

More information

9/10/12. Outline. Part 5. Computational Complexity (2) Examples. (revisit) Properties of Growth-rate functions(1/3)

9/10/12. Outline. Part 5. Computational Complexity (2) Examples. (revisit) Properties of Growth-rate functions(1/3) Outline Part 5. Computational Complexity (2) Complexity of Algorithms Efficiency of Searching Algorithms Sorting Algorithms and Their Efficiencies CS 200 Algorithms and Data Structures 1 2 (revisit) Properties

More information

CSE 143 Lecture 16 (B)

CSE 143 Lecture 16 (B) CSE 143 Lecture 16 (B) Sorting reading: 13.1, 13.3-13.4 slides created by Marty Stepp http://www.cs.washington.edu/143/ Sorting sorting: Rearranging the values in an array or collection into a specific

More information

Data structures. More sorting. Dr. Alex Gerdes DIT961 - VT 2018

Data structures. More sorting. Dr. Alex Gerdes DIT961 - VT 2018 Data structures More sorting Dr. Alex Gerdes DIT961 - VT 2018 Divide and conquer Very general name for a type of recursive algorithm You have a problem to solve: - Split that problem into smaller subproblems

More information

Data Types. Operators, Assignment, Output and Return Statements

Data Types. Operators, Assignment, Output and Return Statements Pseudocode Reference Sheet rev 4/17 jbo Note: This document has been developed by WeTeach_CS, and is solely based on current study materials and practice tests provided on the TEA website. An official

More information

COS 126 General Computer Science Spring Written Exam 1

COS 126 General Computer Science Spring Written Exam 1 COS 126 General Computer Science Spring 2017 Written Exam 1 This exam has 9 questions (including question 0) worth a total of 70 points. You have 50 minutes. Write all answers inside the designated spaces.

More information

COMP2012H Spring 2014 Dekai Wu. Sorting. (more on sorting algorithms: mergesort, quicksort, heapsort)

COMP2012H Spring 2014 Dekai Wu. Sorting. (more on sorting algorithms: mergesort, quicksort, heapsort) COMP2012H Spring 2014 Dekai Wu Sorting (more on sorting algorithms: mergesort, quicksort, heapsort) Merge Sort Recursive sorting strategy. Let s look at merge(.. ) first. COMP2012H (Sorting) 2 COMP2012H

More information

Sorting Goodrich, Tamassia Sorting 1

Sorting Goodrich, Tamassia Sorting 1 Sorting Put array A of n numbers in increasing order. A core algorithm with many applications. Simple algorithms are O(n 2 ). Optimal algorithms are O(n log n). We will see O(n) for restricted input in

More information

Divide-and-Conquer. Divide-and conquer is a general algorithm design paradigm:

Divide-and-Conquer. Divide-and conquer is a general algorithm design paradigm: Presentation for use with the textbook Data Structures and Algorithms in Java, 6 th edition, by M. T. Goodrich, R. Tamassia, and M. H. Goldwasser, Wiley, 2014 Merge Sort 7 2 9 4 2 4 7 9 7 2 2 7 9 4 4 9

More information

Subset sum problem and dynamic programming

Subset sum problem and dynamic programming Lecture Notes: Dynamic programming We will discuss the subset sum problem (introduced last time), and introduce the main idea of dynamic programming. We illustrate it further using a variant of the so-called

More information

Chapter 6. Arrays. Array Basics Arrays in Classes and Methods Programming with Arrays and Classes Sorting Arrays Multidimensional Arrays

Chapter 6. Arrays. Array Basics Arrays in Classes and Methods Programming with Arrays and Classes Sorting Arrays Multidimensional Arrays Chapter 6 Arrays Array Basics Arrays in Classes and Methods Programming with Arrays and Classes Sorting Arrays Multidimensional Arrays Chapter 6 Java: an Introduction to Computer Science & Programming

More information

Sorting and Selection

Sorting and Selection Sorting and Selection Introduction Divide and Conquer Merge-Sort Quick-Sort Radix-Sort Bucket-Sort 10-1 Introduction Assuming we have a sequence S storing a list of keyelement entries. The key of the element

More information

Sorting. Bubble Sort. Pseudo Code for Bubble Sorting: Sorting is ordering a list of elements.

Sorting. Bubble Sort. Pseudo Code for Bubble Sorting: Sorting is ordering a list of elements. Sorting Sorting is ordering a list of elements. Types of sorting: There are many types of algorithms exist based on the following criteria: Based on Complexity Based on Memory usage (Internal & External

More information

2 marks. class q1c{ class point{ int p,q; point(int p, int q){ this.p=p; this.q=q; } void printpoint(){ System.out.println(this.p+" "+this.

2 marks. class q1c{ class point{ int p,q; point(int p, int q){ this.p=p; this.q=q; } void printpoint(){ System.out.println(this.p+ +this. Question1. What will be the output of the following programs? Give reasons. [4, 7, 4] No credit will be given if you do not give reasons (even if your output is correct). Also, if the reasoning is wrong

More information

About this exam review

About this exam review Final Exam Review About this exam review I ve prepared an outline of the material covered in class May not be totally complete! Exam may ask about things that were covered in class but not in this review

More information

Prelim 2 Solution. CS 2110, November 19, 2015, 5:30 PM Total. Sorting Invariants Max Score Grader

Prelim 2 Solution. CS 2110, November 19, 2015, 5:30 PM Total. Sorting Invariants Max Score Grader Prelim 2 CS 2110, November 19, 2015, 5:30 PM 1 2 3 4 5 6 Total Question True Short Complexity Searching Trees Graphs False Answer Sorting Invariants Max 20 15 13 14 17 21 100 Score Grader The exam is closed

More information

UCS-406 (Data Structure) Lab Assignment-1 (2 weeks)

UCS-406 (Data Structure) Lab Assignment-1 (2 weeks) UCS-40 (Data Structure) Lab Assignment- (2 weeks) Implement the following programs in C/C++/Python/Java using functions a) Insertion Sort b) Bubble Sort c) Selection Sort d) Linear Search e) Binary Search

More information

Algorithms and Applications

Algorithms and Applications Algorithms and Applications 1 Areas done in textbook: Sorting Algorithms Numerical Algorithms Image Processing Searching and Optimization 2 Chapter 10 Sorting Algorithms - rearranging a list of numbers

More information

Practical Session #11 - Sort properties, QuickSort algorithm, Selection

Practical Session #11 - Sort properties, QuickSort algorithm, Selection Practical Session #11 - Sort properties, QuickSort algorithm, Selection Quicksort quicksort( A, low, high ) if( high > low ) pivot partition( A, low, high ) // quicksort( A, low, pivot-1 ) quicksort( A,

More information

Computer Science 385 Analysis of Algorithms Siena College Spring Topic Notes: Divide and Conquer

Computer Science 385 Analysis of Algorithms Siena College Spring Topic Notes: Divide and Conquer Computer Science 385 Analysis of Algorithms Siena College Spring 2011 Topic Notes: Divide and Conquer Divide and-conquer is a very common and very powerful algorithm design technique. The general idea:

More information

You must bring your ID to the exam.

You must bring your ID to the exam. Com S 227 Spring 2017 Topics and review problems for Exam 2 Monday, April 3, 6:45 pm Locations, by last name: (same locations as Exam 1) A-E Coover 2245 F-M Hoover 2055 N-S Physics 0005 T-Z Hoover 1213

More information

Computer Science 252 Problem Solving with Java The College of Saint Rose Spring Topic Notes: Searching and Sorting

Computer Science 252 Problem Solving with Java The College of Saint Rose Spring Topic Notes: Searching and Sorting Computer Science 5 Problem Solving with Java The College of Saint Rose Spring 016 Topic Notes: Searching and Sorting Searching We all know what searching is looking for something. In a computer program,

More information

Administrivia. HW on recursive lists due on Wednesday. Reading for Wednesday: Chapter 9 thru Quicksort (pp )

Administrivia. HW on recursive lists due on Wednesday. Reading for Wednesday: Chapter 9 thru Quicksort (pp ) Sorting 4/23/18 Administrivia HW on recursive lists due on Wednesday Reading for Wednesday: Chapter 9 thru Quicksort (pp. 271-284) A common problem: Sorting Have collection of objects (numbers, strings,

More information

Search,Sort,Recursion

Search,Sort,Recursion Search,Sort,Recursion Searching, Sorting and Recursion Searching Linear Search Inserting into an Array Deleting from an Array Selection Sort Bubble Sort Binary Search Recursive Binary Search Searching

More information

08 A: Sorting III. CS1102S: Data Structures and Algorithms. Martin Henz. March 10, Generated on Tuesday 9 th March, 2010, 09:58

08 A: Sorting III. CS1102S: Data Structures and Algorithms. Martin Henz. March 10, Generated on Tuesday 9 th March, 2010, 09:58 08 A: Sorting III CS1102S: Data Structures and Algorithms Martin Henz March 10, 2010 Generated on Tuesday 9 th March, 2010, 09:58 CS1102S: Data Structures and Algorithms 08 A: Sorting III 1 1 Recap: Sorting

More information

Recursion. Example R1

Recursion. Example R1 Recursion Certain computer problems are solved by repeating the execution of one or more statements a certain number of times. So far, we have implemented the repetition of one or more statements by using

More information

Backward Reasoning: Rule for Assignment. Backward Reasoning: Rule for Sequence. Simple Example. Hoare Logic, continued Reasoning About Loops

Backward Reasoning: Rule for Assignment. Backward Reasoning: Rule for Sequence. Simple Example. Hoare Logic, continued Reasoning About Loops Backward Reasoning: Rule for Assignment Hoare Logic, continued Reasoning About Loops { wp( x=expression,q) x = expression; { Q Rule: the weakest precondition wp( x=expression,q) is Q with all occurrences

More information