Outline. Computer programming. Cross product algorithm. Cross product. Set every element of vector p to 1. Find next element as follows:
|
|
- Evan Carson
- 5 years ago
- Views:
Transcription
1 Outline Computer programming "He who loves practice without theory is like the sailor who boards ship without a ruder and compass and never knows where he may cast." Leonardo da Vinci Applications Combinatorial generation: generating subsets Cross product (Cartesian product) Combinations Permutations Arrangements Power set Simple sorting algorithms Counting sort Insertion sort Shell sort Bubble sort Selection sort T.U. Cluj-Napoca - Computer Programming - lecture - M. Joldoş T.U. Cluj-Napoca - Computer Programming - lecture - M. Joldoş 2 Cross product Considern sets of positive integers: A, A 2,..., A n. Set A i, for i=, 2,..., n has n i elements The cross product (Cartesian product, set direct product, product set) is required. i.e. A A2... A n = A i n i= having elements which will i= n i be generated in a vector, p=[ p p 2... p n ] n Cross product algorithm Set every element of vector p to. This is the first element of the cross product Find next element as follows: Find the highest index i for which p i < n i. If such an index cannot be found then all elements have been generated. Stop Find next element of the cross product as p, p 2, p i -, p i +,,,..., T.U. Cluj-Napoca - Computer Programming - lecture - M. Joldoş T.U. Cluj-Napoca - Computer Programming - lecture - M. Joldoş
2 Cross product implementation. Non recursive Cross product implementation. Non recursive #include <stdio.h> #define MAXN void listproduct(int n, int prodnb, int p[]) int i; printf("\n%d ", prodnb); for (i = ; i <=n; i++) printf(" %2d", p[i]); if ( prodnb % 2 == ) getch(); void crossprodnonrec(int n, int nelem[]) /* n = number of sets; nelem = vector with number of elements per set */ int i, prodnb, p[maxn]; prodnb = ; for (i = ; i <= n; i++) p[i] = ; listproduct(n, prodnb, p); i = n; while ( i > ) p[i]++; // find highest such as p[i] > nelem[i] if (p[i] > nelem[i]) p[i] = ; i--; prodnb++; listproduct(n, prodnb, p); i = n; int main(int argc, char *argv[]) int i, n, nelem[maxn]; printf("\nnumber of sets [<%d]=", MAXN); scanf("%d", &n); for (i = ; i <= n; i++) printf("number of elements in set %d=", i); scanf("%d", &nelem[i]); printf("\nthe members of the cross product"); printf("\nno. Elements"); crossprodnonrec(n, nelem); getchar(); return ; T.U. Cluj-Napoca - Computer Programming - lecture - M. Joldoş 5 T.U. Cluj-Napoca - Computer Programming - lecture - M. Joldoş 6 Cross product implementation. Recursive #include <stdio.h> #include <conio.h> #define MAXN int prodnb, p[maxn], nelem[maxn]; void listproduct(int n) int i; printf("\n%d ", prodnb); for (i = ; i <=n; i++) printf(" %2d", p[i]); if ( prodnb % 2 == ) getch(); void crossprodrec(int n, int i) /* n = number of sets; nelem = vector with number of elements per set */ int j; for (j = ; j <=nelem[i]; j++) p[i] = j; if (i< n) crossprodrec(n, i+); prodnb++; listproduct(n); T.U. Cluj-Napoca - Computer Programming - lecture - M. Joldoş 7 Cross product implementation. Recursive int main(int argc, char *argv[]) int i, n; printf("\nnumber of sets [<%d]=", MAXN); scanf("%d", &n); for (i = ; i <= n; i++) printf("number of elements in set %d=", i); scanf("%d", &nelem[i]); printf("\nthe members of the cross product"); printf("\nno. Elements"); crossprodrec(n, ); getch(); return ; T.U. Cluj-Napoca - Computer Programming - lecture - M. Joldoş 8
3 Combinations Let P be a set of n elements All ways of picking k unordered elements of the n elements = generating all subsets with k n elements of P such as any two subsets are distinct The number of subsets is the binomial coefficient or choice number and read "n choose k " T.U. Cluj-Napoca - Computer Programming - lecture - M. Joldoş 9 Combinations algorithm First subset is p=, 2,..., k Given a subset, its successor is found as follows: Going from k down to find index i which satisfies the relationships pi < n k + i pi+ = n k + i +... pk = n p = n k Successor set is: p, p2,..., pi +, pi + 2,..., pi + n k + The last subset is: n k +, n k + 2,..., n, n T.U. Cluj-Napoca - Computer Programming - lecture - M. Joldoş Combinations algorithm implementation. Non recursive void combinnonrec(int n, int k) int p[maxn]; int i, j, combinnb; for (i=; i <=k; i++) p[i]=i; /* first combination */ listcombin(k, combinnb, p); i = k; while (i > ) /* generate the next combinations */ p[i]++; // find index satisfying relation set if (p[i] > n k + i) i--; for (j = i + ; ; j <= k; j++) p[j]=p[j-] + ; combinnb++; listcombin(k, combinnb, p); i = k; T.U. Cluj-Napoca - Computer Programming - lecture - M. Joldoş Combinations algorithm implementation. Recursive void combinrec(int n, int k, int i) int j; for (j = p[i-]+; j <= n-k+i; j++) p[i] = j; if (i < k) combinrec(n, k, i+); combinnb++; listcombin(k, combinnb, p); Notes Array p, and combinnb must be global Invocation is: combinrec(n, k, ) T.U. Cluj-Napoca - Computer Programming - lecture - M. Joldoş 2
4 Generating Permutations For instance 52 is the permutation that maps to, 2 to 5, to 2, to, and 5 to. We know that there are 7! permutations on,2,,,5,6,7. Suppose we want to list them all. Is there an efficient way to do so? It turns out to be fairly simple to list them lexicographically. The only hard question is, given one permutation, how do we find the next one? The lexicographically first permutation is 2... n and the last is n n -... Generating Permutations It is intuitively reasonable that if the final digits of a permutation are in descending order, then no rearrangement will make them larger. For instance in 2576 we cannot produce a larger number by rearranging the 76. Instead we must increase the next most significant digit (the 5) by the next larger digit in 76 (the 6). Then the remaining digits (the 5 and the 7) must be arranged to form the smallest number possible. Thus the next permutation in lexicographic order is T.U. Cluj-Napoca - Computer Programming - lecture - M. Joldoş T.U. Cluj-Napoca - Computer Programming - lecture - M. Joldoş Generating permutations in lexicographical order a. First permutation is p =, 2,... n b. Given vector p=[p p 2... p n ] the next permutation is found as follows:. Look from n down to for the highest valued index which satisfies the relationships: p i <p i + p i + > p i +2 >...> p n 2. Find the maximum element, p k > p i of p i +, p i +2,..., p n. Swap p k with p i. Revert p i +, p i +2,..., p n by swapping p i+ and p n, p i+2 and p n-, a.s.o. Permutations implementation. Non recursive void permnonrec(int n) int p[maxn]; int i, k, permnb = ; /* first permutation, step a */ for (i = ; i <= n; i++) p[i] = i; listperm(n, ++permnb, p); do /* generate the next permutations */ i = n - ; while (p[i] > p[i+] && i > ) i--; /* step b */ if (i > ) for (k = n; p[i] > p[k]; k--); /* step b2 */ swap( &p[i], &p[k] ); /* step b */ revert(p, i, n, (n - i ) / 2); listperm(n, ++permnb, p); while (i > ); void swap(int *i, int *j) int temp; temp = *i; *i = *j; *j = temp; void revert(int p[], int i, int n, int k) int j; for (j = ; j <= k; j++) swap(p[i+j], p[n+-j]); T.U. Cluj-Napoca - Computer Programming - lecture - M. Joldoş 5 T.U. Cluj-Napoca - Computer Programming - lecture - M. Joldoş 6
5 A note on swapping Swapping integers in place void swap(int *i, int *j) *i += *j; // i == i + j *j = *i - *j;// j == i + j j == i *i -= *j; // i == i + j i == j void swap(int *i, int *j) *i ^= j; // a == a^b; *j ^= *i;// b == b^(a^b) *i ^= *j;// a == (a^b)^(b^(a^b)) Second version based on proof on the nearby table, where a and b are bit positions a b a^b final b b^(a^b) T.U. Cluj-Napoca - Computer Programming - lecture - M. Joldoş 7 final a (a^b)^(b^(a^b)) Permutations implementation. Recursive void permrec(int nb) int i, j; if ( nb == ) permnb++; listperm(); permrec(nb ); for (i = ; i <= nb ; i++) swap( p[i], p[nb] ); permrec(nb ); swap( p[i], p[nb] ); Notes Generates recursively permutations of elements p p 2... p n- with p n in position n Then swaps p i with p n for i =..n-, and generates all permutations Array p, n, and permnb must be globals First permutation must be initialized separately Invocation: permrec(n) Order is not loxicographic T.U. Cluj-Napoca - Computer Programming - lecture - M. Joldoş 8 Generating arrangements For set p=, 2,..., n and k n, positive generate all k-subsets such any two subsets must differ either in the composing elements or in their order Algorithm idea: generate all combinations of n elements taken k, and, for each combination generate the k! permutations T.U. Cluj-Napoca - Computer Programming - lecture - M. Joldoş 9 Generating arrangements implementation void arrange(int n, int m, int i) int j, k, r; for (j = p[i-] + ; j <= n - m + i; j++) // recursively generate combinations p[i] = j; if (i < m) arrange(n, m, i + ); arrnb++; listarrang(m, p); for (k = ; k <= m; k++) v[k] = p[k]; // save combination do // nonrecursively permute combination k = m - ; while (v[k] > v[k + ] && k > ) k--; if (k > ) for (r = m; v[k] > v[r]; r--); swap(&v[k], &v[r]); revert(k, m, (m - k) / 2); arrnb++; listarrang(m, v); while (k > ); T.U. Cluj-Napoca - Computer Programming - lecture - M. Joldoş 2
6 Generating a power set We wish to generate all 2 n subsets of set A=a,...,a n (power set) All subsets of A=a,...,a n can be divided to two groups Ones that contain a n Ones that does not contain a n Ones that does not contain a n are all subsets of a,...,a n- When we have all subsets of a,...,a n- we can create all subsets of a,...,a n by adding all elements with a n inserted T.U. Cluj-Napoca - Computer Programming - lecture - M. Joldoş 2 Generating a power set Again, we try to generate all subsets without generating power sets of smaller sets We can associate 2 n subsets of n elements set A=a,...,a n with 2 n bit strings b...b n b i = if a i is element of set b i = if a i is not element of set For elements set a, a 2, a the empty set the set itself subset a, a 2 We can create bit strings by generating binary numbers from to 2 n - Example: Bit strings Subsets a a 2 a 2,a a a,a a,a 2 a,a 2,a T.U. Cluj-Napoca - Computer Programming - lecture - M. Joldoş 22 Generating a power set. Non recursive Generating a power set. Recursive void allsubsetsnr(int n) int i, setnb, p[maxn]; // p[i]= if element i is a member, // i.e p is a characteristic vector setnb=; for (i=; i<=n; i++) p[i]=; /*empty set */ listset(n, setnb, p); for (i=n; i>; ) /* generate next subsets */ if (p[i] == ) p[i] = ; setnb++; listset(n, setnb, p); i = n; p[i] = ; i--; void allsubsetsrec(int n, int i) int j; for (j=; j <= ; j++) p[i] = j; if (i < n) allsubsetsrec(n, i+); setnb++; listset(n, setnb); void listset(int n, int setnb) int i; printf("\n%d ", setnb); for (i = ; i <=n; i++) if (p[i] == ) printf(" %2d,", i); printf("\b "); if ( setnb % 2 == ) getch(); Note that array p and variable setnb must be global T.U. Cluj-Napoca - Computer Programming - lecture - M. Joldoş 2 T.U. Cluj-Napoca - Computer Programming - lecture - M. Joldoş 2
7 Sorting We assume that objects to be sorted are records consisting of one or more fields. One of the fields, called the key is of a type for which a linear ordering relationship < is defined. The sorting problem: to arrange a sequence of records so that the values of their key fields form a nondecreasing sequence, i.e. for records r, r 2,..., r n with key values k, k 2,..., k n respectively, we must produce the same records in an order such that T.U. Cluj-Napoca - Computer Programming - lecture - M. Joldoş 25 Sort. Auxiliary routines void swap( void *px, void *py, size_t size) /* swap exchanges the values of x and y */ void *ptemp; if (NULL==(ptemp=malloc(size))) fatalerror("no memory"); memcpy(ptemp, px, size); memcpy(px, py, size); memcpy(py, ptemp, size); free(ptemp); /* swap */ int cmpkey(keyt pk, keyt pk2, size_t size) // example for objects stored in high to low value order return(memcmp(pk, pk2, size)); T.U. Cluj-Napoca - Computer Programming - lecture - M. Joldoş 26 Counting Sort CountingSort is an algorithm which requires that the keys positive integers in the range of to k and exploits the fact that keys can be used for indexing an array, hence it is not based on comparison. First we count the occurrences of each key of the array A and store the count in array C: A = C = 2 Then we determine the number of elements which are less than or equal to each of the keys by calculating the prefix sums: C = 6 Counting Sort We produce the output in sequence B by going through A and determining for each element to which position in B goes by looking that up in C. Then we decrease the entry for that element in C. A = B = C = B = C = B = C = T.U. Cluj-Napoca - Computer Programming - lecture - M. Joldoş 27 T.U. Cluj-Napoca - Computer Programming - lecture - M. Joldoş 28
8 Counting sort implementation variant void countsort(int n) // array A is an array of integer keys int i, j; int b[maxrec]; int c[maxrec]; for (i=; i < n; i++) c[i]=; //init counting vector b[i] = A[i]; // duplicate A // counting for (j = ; j < n; j++) for (i = ; i < j; i++) if (A[i] < A[j])) c[j]++; c[i]++; // rearange vector A for (i = ; i < n; i++) A[c[i]] = b[i]; /* countsort */ Insertion Sort In place sorting algorithm using a table A[..n ] At the beginning of each step i, for i < n, the table consists of: left, sorted part A[..i ] marked element x A[i] right, unsorted part A[i+..n ] The marked element x is inserted in the sorted part; the rest of the sorted part is shifted to the right T.U. Cluj-Napoca - Computer Programming - lecture - M. Joldoş 29 T.U. Cluj-Napoca - Computer Programming - lecture - M. Joldoş Insertion Sort Insertion sort operation void inssort() int i, j; memcpy(a[].key, MINUS_INFINITY, sizeof(keyt)); for (i = 2; i <= n; i++) j = i; while (cmpkey(a[j].key, A[j-].key, sizeof(keyt)) < ) swap( &A[j], &A[j-], sizeof(recordt)); j--; /* inssort */ T.U. Cluj-Napoca - Computer Programming - lecture - M. Joldoş T.U. Cluj-Napoca - Computer Programming - lecture - M. Joldoş 2
9 Shell sort idea Sort in place, using a table A[..n-] Idea InsertionSort only elements at positions i, i+h, i+2h Repeat for i=,,..., h- InsertionSort the result Improvement: iterate on k, decreasing hk Motivation: reduce the maximal shifting distance in each phase. void shellsort() int h, i, j; Shell Sort h = n/2; // set increment value while (h > ) /* sort-by-insertion in increments of h */ for (i = h + ; i <= n; i++) j = i - h; while ( j > ) if ( cmpkey( A[j].key, A[j+h].key,sizeof(keyT) ) > ) swap(&a[j+h], &A[j], sizeof(recordt)); j -= h; j = ; h /= 2; /* shellsort */ T.U. Cluj-Napoca - Computer Programming - lecture - M. Joldoş T.U. Cluj-Napoca - Computer Programming - lecture - M. Joldoş Bubble Sort enum FALSE, TRUE; void bubblesort() int i, j, done = FALSE; for (i = ; i < n &&!done; i++) for (j = n; j > i &&!done; j--) done = TRUE; if (cmpkey(a[j].key, A[j-].key, sizeof(keyt)) < ) swap(&a[j], &A[j-], sizeof(recordt)); done = FALSE; /* bubblesort */ T.U. Cluj-Napoca - Computer Programming - lecture - M. Joldoş 5 Selection Sort void selsort() static keyt lowkey; // the currently smallest key found on a pass // through A[i],..., A[n] int lowindex ; // the position of lowkey int i, j; for (i = ; i < n; i++) /* select the lowest among A[i],..., A[n] and swap it with A[i] */ lowindex = i; memcpy( &lowkey, &A[i].key, sizeof( keyt )); for ( j = i+; j <= n; j++) /* compare each key with current lowkey */ if ( cmpkey( A[j].key, lowkey, sizeof( keyt )) < ) memcpy( &lowkey, &A[j].key, sizeof( keyt )); lowindex = j; swap( &A[i], &A[lowindex], sizeof( recordt )); /* selsort */ T.U. Cluj-Napoca - Computer Programming - lecture - M. Joldoş 6
10 Selection sort operation...and one step more T.U. Cluj-Napoca - Computer Programming - lecture - M. Joldoş 7 Summary Applications Combinatorial generation: generating subsets Cross product (Cartesian product) Combinations Permutations Arrangements Power set Simple sorting algorithms Counting sort Insertion sort Shell sort Bubble sort Selection sort T.U. Cluj-Napoca - Computer Programming - lecture - M. Joldoş 8
Computer programming
Computer programming "He who loves practice without theory is like the sailor who boards ship without a ruder and compass and never knows where he may cast." Leonardo da Vinci T.U. Cluj-Napoca - Computer
More informationComputer Programming
Computer Programming Make everything as simple as possible, but not simpler. Albert Einstein T.U. Cluj-Napoca - Computer Programming - lecture 8 - M. Joldoş 1 Outline Pointers to functions Declaring, using,
More informationUE Algorithmen und Datenstrukturen 1 UE Praktische Informatik 1. Übung 9. Sorting
UE Algorithmen und Datenstrukturen 1 UE Praktische Informatik 1 Übung 9 Sorting Institut für Pervasive Computing Johannes Kepler Universität Linz Altenberger Straße 69, A-4040 Linz Sorting :: Problem given:
More informationChapter 7 Sorting. Terminology. Selection Sort
Chapter 7 Sorting Terminology Internal done totally in main memory. External uses auxiliary storage (disk). Stable retains original order if keys are the same. Oblivious performs the same amount of work
More informationAnalysis 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 informationIosif Ignat, Marius Joldoș Laboratory Guide 5. Functions. FUNCTIONS in C
FUNCTIONS in C 1. Overview The learning objective of this lab session is to: Understand the structure of a C function Understand function calls both using arguments passed by value and by reference Understand
More informationArrays and Applications
Arrays and Applications 60-141: Introduction to Algorithms and Programming II School of Computer Science Term: Summer 2014 Instructor: Dr. Asish Mukhopadhyay What s an array Let a 0, a 1,, a n-1 be a sequence
More informationIosif Ignat, Marius Joldoș Laboratory Guide 4. Statements. STATEMENTS in C
STATEMENTS in C 1. Overview The learning objective of this lab is: To understand and proper use statements of C/C++ language, both the simple and structured ones: the expression statement, the empty statement,
More informationData Structure Lecture#16: Internal Sorting (Chapter 7) U Kang Seoul National University
Data Structure Lecture#16: Internal Sorting (Chapter 7) U Kang Seoul National University U Kang 1 In This Lecture Definition and evaluation measures of sorting Exchange sorting algorithms and their limitations
More informationLecture 6 Sorting and Searching
Lecture 6 Sorting and Searching Sorting takes an unordered collection and makes it an ordered one. 1 2 3 4 5 6 77 42 35 12 101 5 1 2 3 4 5 6 5 12 35 42 77 101 There are many algorithms for sorting a list
More informationSolutions to Assessment
Solutions to Assessment [1] What does the code segment below print? int fun(int x) ++x; int main() int x = 1; fun(x); printf( %d, x); return 0; Answer : 1. The argument to the function is passed by value.
More informationBubble sort starts with very first two elements, comparing them to check which one is greater.
Bubble Sorting: Bubble sort is a simple sorting algorithm. This sorting algorithm is comparison-based algorithm in which each pair of adjacent elements is compared and the elements are swapped if they
More informationSearching Elements in an Array: Linear and Binary Search. Spring Semester 2007 Programming and Data Structure 1
Searching Elements in an Array: Linear and Binary Search Spring Semester 2007 Programming and Data Structure 1 Searching Check if a given element (called key) occurs in the array. Example: array of student
More informationProf. Sushant S Sundikar 1
UNIT 5 The related activities of sorting, searching and merging are central to many computer applications. Sorting and merging provide us with a means of organizing information take advantage of the organization
More informationCOMP 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 informationCS 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 informationSample Problems for Quiz # 2
EE 1301 UMN Introduction to Computing Systems Fall 2013 Sample Problems for Quiz # 2 (with solutions) Here are sample problems to help you prepare for Quiz 2 on Oct. 31. 1. Bit-Level Arithmetic (a) Consider
More informationC Language Part 2 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee
C Language Part 2 (Minor modifications by the instructor) 1 Scope Rules A variable declared inside a function is a local variable Each local variable in a function comes into existence when the function
More information1KOd17RMoURxjn2 CSE 20 DISCRETE MATH Fall
CSE 20 https://goo.gl/forms/1o 1KOd17RMoURxjn2 DISCRETE MATH Fall 2017 http://cseweb.ucsd.edu/classes/fa17/cse20-ab/ Today's learning goals Explain the steps in a proof by mathematical and/or structural
More informationBiostatistics 615/815 Lecture 5: Divide and Conquer Algorithms Sorting Algorithms
Biostatistics 615/815 Lecture 5: Algorithms Algorithms Hyun Min Kang September 20th, 2011 Hyun Min Kang Biostatistics 615/815 - Lecture 5 September 20th, 2011 1 / 30 Recap - An example C++ class #include
More informationProgramming Language B
Programming Language B Takako Nemoto (JAIST) 17 December Takako Nemoto (JAIST) 17 December 1 / 17 A tip for the last homework 1 Do Exercise 9-5 ( 9-5) in p.249 (in the latest edtion). The type of the second
More informationThe complexity of Sorting and sorting in linear-time. Median and Order Statistics. Chapter 8 and Chapter 9
Subject 6 Spring 2017 The complexity of Sorting and sorting in linear-time Median and Order Statistics Chapter 8 and Chapter 9 Disclaimer: These abbreviated notes DO NOT substitute the textbook for this
More informationPriority queues. Priority queues. Priority queue operations
Priority queues March 30, 018 1 Priority queues The ADT priority queue stores arbitrary objects with priorities. An object with the highest priority gets served first. Objects with priorities are defined
More informationStructured programming
Exercises 9 Version 1.0, 13 December, 2016 Table of Contents 1. Remainders from lectures.................................................... 1 1.1. What is a pointer?.......................................................
More informationSorting. Sorting. Stable Sorting. In-place Sort. Bubble Sort. Bubble Sort. Selection (Tournament) Heapsort (Smoothsort) Mergesort Quicksort Bogosort
Principles of Imperative Computation V. Adamchik CS 15-1 Lecture Carnegie Mellon University Sorting Sorting Sorting is ordering a list of objects. comparison non-comparison Hoare Knuth Bubble (Shell, Gnome)
More informationSorting. 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 informationPower Set of a set and Relations
Power Set of a set and Relations 1 Power Set (1) Definition: The power set of a set S, denoted P(S), is the set of all subsets of S. Examples Let A={a,b,c}, P(A)={,{a},{b},{c},{a,b},{b,c},{a,c},{a,b,c}}
More informationCS 137 Part 7. Big-Oh Notation, Linear Searching and Basic Sorting Algorithms. November 10th, 2017
CS 137 Part 7 Big-Oh Notation, Linear Searching and Basic Sorting Algorithms November 10th, 2017 Big-Oh Notation Up to this point, we ve been writing code without any consideration for optimization. There
More informationSearching 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 informationLecture 02 Summary. C/Java Syntax 1/14/2009. Keywords Variable Declarations Data Types Operators Statements. Functions
Lecture 02 Summary C/Java Syntax Keywords Variable Declarations Data Types Operators Statements if, switch, while, do-while, for Functions 1 2 By the end of this lecture, you will be able to identify the
More information8/2/10. Looking for something COMP 10 EXPLORING COMPUTER SCIENCE. Where is the book Modern Interiors? Lecture 7 Searching and Sorting TODAY'S OUTLINE
Looking for something COMP 10 EXPLORING COMPUTER SCIENCE Where is the book Modern Interiors? Lecture 7 Searching and Sorting TODAY'S OUTLINE Searching algorithms Linear search Complexity Sorting algorithms
More informationSorting Algorithms. Dipartimento di Elettronica e Informazione Politecnico di Milano June 5, 2018
Sorting Algorithms Dipartimento di Elettronica e Informazione Politecnico di Milano nicholas.mainardi@polimi.it June 5, 2018 Selection Sort Recall At each iteration, the considered sub-array is composed
More informationC/Java Syntax. January 13, Slides by Mark Hancock (adapted from notes by Craig Schock)
C/Java Syntax 1 Lecture 02 Summary Keywords Variable Declarations Data Types Operators Statements if, switch, while, do-while, for Functions 2 By the end of this lecture, you will be able to identify the
More informationC/Java Syntax. Lecture 02 Summary. Keywords Variable Declarations Data Types Operators Statements. Functions. if, switch, while, do-while, for
C/Java Syntax 1 Lecture 02 Summary Keywords Variable Declarations Data Types Operators Statements if, switch, while, do-while, for Functions 2 1 By the end of this lecture, you will be able to identify
More information1 The sorting problem
Lecture 6: Sorting methods - The sorting problem - Insertion sort - Selection sort - Bubble sort 1 The sorting problem Let us consider a set of entities, each entity having a characteristics whose values
More informationHIGH LEVEL FILE PROCESSING
HIGH LEVEL FILE PROCESSING 1. Overview The learning objectives of this lab session are: To understand the functions used for file processing at a higher level. o These functions use special structures
More informationAlgorithms 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 informationLecture 19 Sorting Goodrich, Tamassia
Lecture 19 Sorting 7 2 9 4 2 4 7 9 7 2 2 7 9 4 4 9 7 7 2 2 9 9 4 4 2004 Goodrich, Tamassia Outline Review 3 simple sorting algorithms: 1. selection Sort (in previous course) 2. insertion Sort (in previous
More informationEECS 2011M: Fundamentals of Data Structures
M: Fundamentals of Data Structures Instructor: Suprakash Datta Office : LAS 3043 Course page: http://www.eecs.yorku.ca/course/2011m Also on Moodle Note: Some slides in this lecture are adopted from James
More informationSorting. 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 informationSorting Algorithms part 1
Sorting Algorithms part 1 1. Bubble sort Description Bubble sort is a simple sorting algorithm. It works by repeatedly stepping through the array to be sorted, comparing two items at a time, swapping these
More informationSample Examination. Family Name:... Other Names:... Signature:... Student Number:...
Family Name:... Other Names:... Signature:... Student Number:... THE UNIVERSITY OF NEW SOUTH WALES SCHOOL OF COMPUTER SCIENCE AND ENGINEERING Sample Examination COMP1917 Computing 1 EXAM DURATION: 2 HOURS
More informationBiostatistics 615/815 Statistical Computing
Biostatistics 615/815 Statistical Computing Hyun Min Kang Januray 6th, 2011 Hyun Min Kang Biostatistics 615/815 - Lecture 1 Januray 6th, 2011 1 / 35 Objectives Understanding computational aspects of statistical
More information1 (15 points) LexicoSort
CS161 Homework 2 Due: 22 April 2016, 12 noon Submit on Gradescope Handed out: 15 April 2016 Instructions: Please answer the following questions to the best of your ability. If you are asked to show your
More informationSorting is ordering a list of objects. Here are some sorting algorithms
Sorting Sorting is ordering a list of objects. Here are some sorting algorithms Bubble sort Insertion sort Selection sort Mergesort Question: What is the lower bound for all sorting algorithms? Algorithms
More informationOutline. Computer Science 331. Three Classical Algorithms. The Sorting Problem. Classical Sorting Algorithms. Mike Jacobson. Description Analysis
Outline Computer Science 331 Classical Sorting Algorithms Mike Jacobson Department of Computer Science University of Calgary Lecture #22 1 Introduction 2 3 4 5 Comparisons Mike Jacobson (University of
More informationCS Sorting Terms & Definitions. Comparing Sorting Algorithms. Bubble Sort. Bubble Sort: Graphical Trace
CS 704 Introduction to Data Structures and Software Engineering Sorting Terms & Definitions Internal sorts holds all data in RAM External sorts use Files Ascending : Low to High Descending : High to Low
More informationSearching an Array: Linear and Binary Search. 21 July 2009 Programming and Data Structure 1
Searching an Array: Linear and Binary Search 21 July 2009 Programming and Data Structure 1 Searching Check if a given element (key) occurs in the array. Two methods to be discussed: If the array elements
More informationCpt S 122 Data Structures. Sorting
Cpt S 122 Data Structures Sorting Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Sorting Process of re-arranging data in ascending or descending order Given
More informationIntroduction. Sorting. Definitions and Terminology: Program efficiency. Sorting Algorithm Analysis. 13. Sorting. 13. Sorting.
Sorting Introduction Slides. Table of Contents. Introduction 3. Bubblesort 4. Bubblesort Complexity 5. Bubblesort Complexity (cont) 6. Selection Sort 7. Selection Sort Complexity 8. Duplex Selection Sort
More informationSorting Algorithms. Array Data is being arranged in ascending order using the bubble sort algorithm. #1 #2 #3 #4 #5 #6 #7
Sorting Algorithms One of the fundamental problems of computer science is ordering a list of items. There s a plethora of solutions to this problem, known as sorting algorithms. Some sorting algorithms
More informationLecture 5 Sorting Arrays
Lecture 5 Sorting Arrays 15-122: Principles of Imperative Computation (Spring 2018) Frank Pfenning, Rob Simmons We begin this lecture by discussing how to compare running times of functions in an abstract,
More informationComputers Programming Course 6. Iulian Năstac
Computers Programming Course 6 Iulian Năstac Recap from previous course Data types four basic arithmetic type specifiers: char int float double void optional specifiers: signed, unsigned short long 2 Recap
More informationDATA STRUCTURES AND ALGORITHMS. Sorting algorithms (insertion sort, bubble sort, selection sort)
DATA STRUCTURES AND ALGORITHMS Sorting algorithms (insertion sort, bubble sort, selection sort) Summary of the previous lecture Recursion Definition Examples Factorial Fibonacci Hanoi tower Printing of
More informationSorting. 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 informationIntroduction. Sorting. Table of Contents
Sorting Introduction Table of Contents Introduction Bubblesort Selection Sort Duplex Selection Sort Duplex Selection Sort (cont) Comparison Analysis Comparison Analysis (cont) Time Analysis Time Analysis
More informationApplied Programming and Computer Science, DD2325/appcs15 PODF, Programmering och datalogi för fysiker, DA7011
Applied Programming and Computer Science, DD2325/appcs15 PODF, Programmering och datalogi för fysiker, DA7011 Autumn 2015 Lecture 3, Simple C programming M. Eriksson (with contributions from A. Maki and
More informationOutline. Computer Programming. Structure of a function. Functions. Function prototype. Structure of a function. Functions
Outline Computer Programming Make everything as simple as possible, but not simpler. Albert Einstein Functions Structure of a function Function invocation Parameter passing Functions as parameters Variable
More informationO(n): printing a list of n items to the screen, looking at each item once.
UNIT IV Sorting: O notation efficiency of sorting bubble sort quick sort selection sort heap sort insertion sort shell sort merge sort radix sort. O NOTATION BIG OH (O) NOTATION Big oh : the function f(n)=o(g(n))
More informationBiostatistics 615/815 - Lecture 2 Introduction to C++ Programming
Biostatistics 615/815 - Lecture 2 Introduction to C++ Programming Hyun Min Kang September 6th, 2012 Hyun Min Kang Biostatistics 615/815 - Lecture 2 September 6th, 2012 1 / 31 Last Lecture Algorithms are
More informationLecture 16. Daily Puzzle. Functions II they re back and they re not happy. If it is raining at midnight - will we have sunny weather in 72 hours?
Lecture 16 Functions II they re back and they re not happy Daily Puzzle If it is raining at midnight - will we have sunny weather in 72 hours? function prototypes For the sake of logical clarity, the main()
More informationData Structures and Algorithms (DSA) Course 12 Trees & sort. Iulian Năstac
Data Structures and Algorithms (DSA) Course 12 Trees & sort Iulian Năstac Depth (or Height) of a Binary Tree (Recapitulation) Usually, we can denote the depth of a binary tree by using h (or i) 2 3 Special
More informationCS 506, Sect 002 Homework 5 Dr. David Nassimi Foundations of CS Due: Week 11, Mon. Apr. 7 Spring 2014
CS 506, Sect 002 Homework 5 Dr. David Nassimi Foundations of CS Due: Week 11, Mon. Apr. 7 Spring 2014 Study: Chapter 4 Analysis of Algorithms, Recursive Algorithms, and Recurrence Equations 1. Prove the
More informationSorting. 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 informationECE264 Spring 2013 Final Exam, April 30, 2013
ECE264 Spring 2013 Final Exam, April 30, 2013 In signing this statement, I hereby certify that the work on this exam is my own and that I have not copied the work of any other student while completing
More informationSorting 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 informationUNIT 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 informationUsing pointers with functions
Using pointers with functions Recall that our basic use of functions so fare provides for several possibilities. A function can 1. take one or more individual variables as inputs and return a single variable
More informationThe University Of Michigan. EECS402 Lecture 07. Andrew M. Morgan. Sorting Arrays. Element Order Of Arrays
The University Of Michigan Lecture 07 Andrew M. Morgan Sorting Arrays Element Order Of Arrays Arrays are called "random-access" data structures This is because any element can be accessed at any time Other
More informationECE 15 Fall 15 Final Solutions
ECE 15 Fall 15 Final Solutions This is a closed-book exam: no notes, books, calculators, cellphones, or friends are allowed. In problems 2 7, you can assume that the user s input is correct. User input
More informationComparison Sorts. Chapter 9.4, 12.1, 12.2
Comparison Sorts Chapter 9.4, 12.1, 12.2 Sorting We have seen the advantage of sorted data representations for a number of applications Sparse vectors Maps Dictionaries Here we consider the problem of
More informationLecture 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 informationProcedural programming with C
Procedural programming with C Dr. C. Constantinides Department of Computer Science and Software Engineering Concordia University Montreal, Canada August 11, 2016 1 / 77 Functions Similarly to its mathematical
More informationDC104 DATA STRUCTURE JUNE Q.2 a. If you are using C language to implement the heterogeneous linked list, what pointer type will you use?
Q.2 a. If you are using C language to implement the heterogeneous linked list, what pointer type will you use? The heterogeneous linked list contains different data types in its nodes and we need a link
More informationExponentiation. Evaluation of Polynomial. A Little Smarter. Horner s Rule. Chapter 5 Recursive Algorithms 2/19/2016 A 2 M = (A M ) 2 A M+N = A M A N
Exponentiation Chapter 5 Recursive Algorithms A 2 M = (A M ) 2 A M+N = A M A N quickpower(a, N) { if (N == 1) return A; if (N is even) B = quickpower(a, N/2); retrun B*B; return A*quickPower(A, N-1); slowpower(a,
More informationArrays and Pointers. CSE 2031 Fall November 11, 2013
Arrays and Pointers CSE 2031 Fall 2013 November 11, 2013 1 Arrays l Grouping of data of the same type. l Loops commonly used for manipulation. l Programmers set array sizes explicitly. 2 Arrays: Example
More informationUnit 6 Chapter 15 EXAMPLES OF COMPLEXITY CALCULATION
DESIGN AND ANALYSIS OF ALGORITHMS Unit 6 Chapter 15 EXAMPLES OF COMPLEXITY CALCULATION http://milanvachhani.blogspot.in EXAMPLES FROM THE SORTING WORLD Sorting provides a good set of examples for analyzing
More informationLecture 9: Sorting Algorithms
Lecture 9: Sorting Algorithms Bo Tang @ SUSTech, Spring 2018 Sorting problem Sorting Problem Input: an array A[1..n] with n integers Output: a sorted array A (in ascending order) Problem is: sort A[1..n]
More informationIndian Institute of Technology Kharagpur Programming and Data Structures (CS10001) Autumn : Mid-Semester Examination
Indian Institute of Technology Kharagpur Programming and Data Structures (CS10001) Autumn 2017-18: Mid-Semester Examination Time: 2 Hours Full Marks: 60 INSTRUCTIONS 1. Answer ALL questions 2. Please write
More informationMTH 307/417/515 Final Exam Solutions
MTH 307/417/515 Final Exam Solutions 1. Write the output for the following programs. Explain the reasoning behind your answer. (a) #include int main() int n; for(n = 7; n!= 0; n--) printf("n =
More informationComputer Science & Engineering 150A Problem Solving Using Computers
Computer Science & Engineering 150A Problem Solving Using Computers Lecture 06 - Stephen Scott Adapted from Christopher M. Bourke 1 / 30 Fall 2009 Chapter 8 8.1 Declaring and 8.2 Array Subscripts 8.3 Using
More informationA. Year / Module Semester Subject Topic 2016 / V 2 PCD Pointers, Preprocessors, DS
Syllabus: Pointers and Preprocessors: Pointers and address, pointers and functions (call by reference) arguments, pointers and arrays, address arithmetic, character pointer and functions, pointers to pointer,initialization
More informationInformatica e Sistemi in Tempo Reale
Informatica e Sistemi in Tempo Reale Introduction to C programming Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa October 5, 2011 G. Lipari (Scuola Superiore Sant Anna) Introduction
More informationComputer Science E-119 Practice Midterm
Name Computer Science E-119 Practice Midterm This exam consists of two parts. Part I has 5 multiple-choice questions worth 3 points each. Part II consists of 3 problems; show all your work on these problems
More informationarxiv: v3 [math.co] 9 Jan 2015
Subset-lex: did we miss an order? arxiv:1405.6503v3 [math.co] 9 Jan 2015 Jörg Arndt, Technische Hochschule Nürnberg January 12, 2015 Abstract We generalize a well-known algorithm for the
More informationFundamentals of Programming
Fundamentals of Programming Introduction to the C language Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa February 29, 2012 G. Lipari (Scuola Superiore Sant Anna) The C language
More informationSorting. 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 informationDiscrete Mathematics. Kruskal, order, sorting, induction
Discrete Mathematics wwwmifvult/~algis Kruskal, order, sorting, induction Kruskal algorithm Kruskal s Algorithm for Minimal Spanning Trees The algorithm constructs a minimal spanning tree as follows: Starting
More informationC: Pointers. C: Pointers. Department of Computer Science College of Engineering Boise State University. September 11, /21
Department of Computer Science College of Engineering Boise State University September 11, 2017 1/21 Pointers A pointer is a variable that stores the address of another variable. Pointers are similar to
More informationPointers. Pointers. Pointers (cont) CS 217
Pointers CS 217 Pointers Variables whose values are the addresses of variables Operations address of (reference) & indirection (dereference) * arithmetic +, - Declaration mimics use char *p; *p is a char,
More informationArmide Documentation. Release Kyle Mayes
Armide Documentation Release 0.3.1 Kyle Mayes December 19, 2014 Contents 1 Introduction 1 1.1 Features.................................................. 1 1.2 License..................................................
More informationESc101: Pointers and Arrays
ESc101: Pointers and Arrays Instructor: Krithika Venkataramani Semester 2, 2011-2012 1 The content of some of these slides are from the lecture slides of Prof. Arnab Bhattacharya 2 1 Movie Theater Seat
More informationArrays and Pointers. Arrays. Arrays: Example. Arrays: Definition and Access. Arrays Stored in Memory. Initialization. EECS 2031 Fall 2014.
Arrays Arrays and Pointers l Grouping of data of the same type. l Loops commonly used for manipulation. l Programmers set array sizes explicitly. EECS 2031 Fall 2014 November 11, 2013 1 2 Arrays: Example
More informationIndian Institute of Technology Kharagpur Programming and Data Structures (CS10001) Autumn : End-Semester Examination
Indian Institute of Technology Kharagpur Programming and Data Structures (CS10001) Autumn 2017-18: End-Semester Examination Time: 3 Hours Full Marks: 100 INSTRUCTIONS 1. Answer ALL questions. 2. Please
More informationElementary Sorting Algorithms
Elementary Sorting Algorithms COMP1927 16x1 Sedgewick Chapter 6 WARM UP EXERCISE: HANDSHAKE PROBLEM In a room of n people, how many different handshakes are possible? 0 + 1 + 2 + + (n-1) Using Maths formula:
More informationYour favorite blog : (popularly known as VIJAY JOTANI S BLOG..now in facebook.join ON FB VIJAY
Course Code : BCS-042 Course Title : Introduction to Algorithm Design Assignment Number : BCA(IV)-042/Assign/14-15 Maximum Marks : 80 Weightage : 25% Last Date of Submission : 15th October, 2014 (For July
More informationGreedy Algorithms. Algorithms
Greedy Algorithms Algorithms Greedy Algorithms Many algorithms run from stage to stage At each stage, they make a decision based on the information available A Greedy algorithm makes decisions At each
More informationCS2223: Algorithms Sorting Algorithms, Heap Sort, Linear-time sort, Median and Order Statistics
CS2223: Algorithms Sorting Algorithms, Heap Sort, Linear-time sort, Median and Order Statistics 1 Sorting 1.1 Problem Statement You are given a sequence of n numbers < a 1, a 2,..., a n >. You need to
More informationFORTH SEMESTER DIPLOMA EXAMINATION IN ENGINEERING/ TECHNOLIGY- MARCH, 2012 DATA STRUCTURE (Common to CT and IF) [Time: 3 hours
TED (10)-3071 Reg. No.. (REVISION-2010) (Maximum marks: 100) Signature. FORTH SEMESTER DIPLOMA EXAMINATION IN ENGINEERING/ TECHNOLIGY- MARCH, 2012 DATA STRUCTURE (Common to CT and IF) [Time: 3 hours PART
More informationCS113: Lecture 5. Topics: Pointers. Pointers and Activation Records
CS113: Lecture 5 Topics: Pointers Pointers and Activation Records 1 From Last Time: A Useless Function #include void get_age( int age ); int age; get_age( age ); printf( "Your age is: %d\n",
More information