Sorting. Simple Sorting As you are probably aware, there are many different sorting algorithms: selection sort, insertion sort, bubble sort, heap sort,

Slides:



Advertisements
Similar presentations
Arrays A list is an ordered collection of scalars. An array is a variable that holds a list. Arrays have a minimum size of 0 and a very large maximum size.
Advertisements

Programming with App Inventor Computing Institute for K-12 Teachers Summer 2012 Workshop.
References and Data Structures. References Just as in C, you can create a variable that is a reference (or pointer) to another variable. That is, it contains.
Quick Sort, Shell Sort, Counting Sort, Radix Sort AND Bucket Sort
CPS120: Introduction to Computer Science Searching and Sorting.
LING/C SC/PSYC 438/538 Lecture 4 Sandiway Fong. Administrivia Homework 1 graded – you should have gotten an from me.
Input from STDIN STDIN, standard input, comes from the keyboard. STDIN can also be used with file re-direction from the command line. For instance, if.
CS 330 Programming Languages 10 / 14 / 2008 Instructor: Michael Eckmann.
Topic 9 – Introduction To Arrays. CISC105 – Topic 9 Introduction to Data Structures Thus far, we have seen “simple” data types. These refers to a single.
Hashes a “hash” is another fundamental data structure, like scalars and arrays. Hashes are sometimes called “associative arrays”. Basically, a hash associates.
CS 330 Programming Languages 10 / 11 / 2007 Instructor: Michael Eckmann.
Logical Operators Java provides two binary logical operators (&& and ||) that are used to combine boolean expressions. Java also provides one unary (!)
1 CS 201 Passing Function as Parameter & Array Debzani Deb.
Scripting Languages Perl Chapter #4 Subroutines. Writing your own Functions Functions is a programming language serve tow purposes: –They allow you to.
Perl File I/O and Arrays. File I/O Perl allows to open a file to read, write, or append As well as pipe input or output to another program. —We get to.
College Algebra Exam 2 Material.
CHAPTER 7: SORTING & SEARCHING Introduction to Computer Science Using Ruby (c) Ophir Frieder at al 2012.
by Chris Brown under Prof. Susan Rodger Duke University June 2012
Comp 249 Programming Methodology Chapter 15 Linked Data Structure - Part B Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
Lists in Python.
Perl Tutorial Presented by Pradeepsunder. Why PERL ???  Practical extraction and report language  Similar to shell script but lot easier and more powerful.
CS212: DATA STRUCTURES Lecture 10:Hashing 1. Outline 2  Map Abstract Data type  Map Abstract Data type methods  What is hash  Hash tables  Bucket.
LING/C SC/PSYC 438/538 Lecture 4 Sandiway Fong. Continuing with Perl Homework 3: first Perl homework – due Sunday by midnight – one PDF file, by .
Meet Perl, Part 2 Flow of Control and I/O. Perl Statements Lots of different ways to write similar statements –Can make your code look more like natural.
Flow of Control Part 1: Selection
PHP Conditional Statements Conditional statements in PHP are used to perform different actions based on different conditions. Conditional Statements Very.
Copyright © 2010 Certification Partners, LLC -- All Rights Reserved Perl Specialist.
Simple Iterative Sorting Sorting as a means to study data structures and algorithms Historical notes Swapping records Swapping pointers to records Description,
Built-in Data Structures in Python An Introduction.
Perl Language Yize Chen CS354. History Perl was designed by Larry Wall in 1987 as a text processing language Perl has revised several times and becomes.
Data TypestMyn1 Data Types The type of a variable is not set by the programmer; rather, it is decided at runtime by PHP depending on the context in which.
1 2. Program Construction in Java. 2.9 Sorting 3 The need Soritng into categories is relatively easy (if, else if, switch); here we consider sorting.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Selection Statements Selection Switch Conditional.
Python uses boolean variables to evaluate conditions. The boolean values True and False are returned when an expression is compared or evaluated.
Prof. Alfred J Bird, Ph.D., NBCT Office – McCormick 3rd floor 607 Office Hours – Tuesday and.
Computer Programming for Biologists Class 3 Nov 13 th, 2014 Karsten Hokamp
CS 105 Perl: Data Types Nathan Clement 15 May 2014.
Perl Tutorial. Why PERL ??? Practical extraction and report language Similar to shell script but lot easier and more powerful Easy availablity All details.
Perl Chapter 5 Hashes. Outside of world of Perl, know as associative arrays Also called hash tables Perl one of few languages that has hashes built-in.
Copyright © 2003 ProsoftTraining. All rights reserved. Perl Fundamentals.
Topic 4:Subroutines CSE2395/CSE3395 Perl Programming Learning Perl 3rd edition chapter 4, pages 56-72, Programming Perl 3rd edition pages 80-83,
Lecture 26: Reusable Methods: Enviable Sloth. Creating Function M-files User defined functions are stored as M- files To use them, they must be in the.
UNIT 5.  The related activities of sorting, searching and merging are central to many computer applications.  Sorting and merging provide us with a.
Scripting Languages Diana Trandab ă ț Master in Computational Linguistics - 1 st year
A Few More Functions. One more quoting operator qw// Takes a space separated sequence of words, and returns a list of single-quoted words. –no interpolation.
 2007 Pearson Education, Inc. All rights reserved C Arrays.
Introduction to Perl NICOLE VECERE. Background General Purpose Language ◦ Procedural, Functional, and Object-oriented Developed for text manipulation.
Introduction to Perl. What is Perl Perl is an interpreted language. This means you run it through an interpreter, not a compiler. Similar to shell script.
Validation using Regular Expressions. Regular Expression Instead of asking if user input has some particular value, sometimes you want to know if it follows.
Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 1 Introduction An array is a collection of identical boxes.
An Introduction to Java – Part 1 Erin Hamalainen CS 265 Sec 001 October 20, 2010.
CS190/295 Programming in Python for Life Sciences: Lecture 6 Instructor: Xiaohui Xie University of California, Irvine.
CPS120: Introduction to Computer Science Decision Making in Programs.
Data Structures Arrays and Lists Part 2 More List Operations.
BINF 634 Fall LECTURE061 Outline Lab 1 (Quiz 3) Solution Program 2 Scoping Algorithm efficiency Sorting Hashes Review for midterm Quiz 4 Outline.
The Scripting Programming Language
Introduction to Arrays. Learning Objectives By the end of this lecture, you should be able to: – Understand what an array is – Know how to create an array.
CSC 4630 Perl 3 adapted from R. E. Beck. Problem But we worked on it first: Input: Read from a text file named in a command line argument Output: List.
Quiz 3 Topics Functions – using and writing. Lists: –operators used with lists. –keywords used with lists. –BIF’s used with lists. –list methods. Loops.
Chapter 17 Arrays Perl to denote an array, for = (10, 20, 30, 50); Array subscripts are number from 0. Array elements require scalar.
References and Data Structures
Discussion 4 eecs 183 Hannah Westra.
Arrays: Checkboxes and Textareas
Miscellaneous Items Loop control, block labels, unless/until, backwards syntax for “if” statements, split, join, substring, length, logical operators,
LING/C SC/PSYC 438/538 Lecture 4 Sandiway Fong.
MATLAB: Structures and File I/O
Conditions and Ifs BIS1523 – Lecture 8.
CISC101 Reminders Assn 3 due tomorrow, 7pm.
Selection Statements.
CISC101 Reminders Assignment 3 due today.
Presentation transcript:

Sorting

Simple Sorting As you are probably aware, there are many different sorting algorithms: selection sort, insertion sort, bubble sort, heap sort, quick sort, etc. You can spend a lot of time writing sort functions if you are so inclined. However, most of us have better things to do, and so Perl provides a good general purpose “sort” function, that uses the standard quick sort algorithm. In most cases it will be quite efficient and fast enough for your purposes. By default, the Perl sort function sorts by ASCII order. Thus, the command = puts the elements into ASCII-sorted order

Sort Function The way in which the “sort” determines ordering can be altered by putting a user- defined subroutine or a block of code between the word “sort” and the list (or array) of things to be sorted: sort sort {code The subroutine or block goes through the array and compares each pair of elements in the array. It returns a negative number if the first element is less than the second, zero if the two elements are equal, and a positive number if the first element is greater than the second element. The input to the subroutine or block is fixed: two variables, called $a and $b. Note that these names are fixed: $a is the first element to be compared, and $b is the second element. $a and $b should not be modified by the subroutine. A simple comparison bloc for a numerical sort: sort { $a - $b If $a (first element) is greater that $b, a positive number is returned; 0 is returned if they are equal, and a negative number is returned if $b is greater than $a.

Built-in Comparison Operators Perl includes 2 built-in operators that give the correct results for sorting numbers or strings. For numerical comparisons, (sometimes called the “spaceship” operator) is used. The standard numerical sort is written: sort {$a For string comparisons, cmp is used. For an ASCII sort you can use the following (although it is the default and not necessary to write is a simple sort): sort {$a cmp $b

Blocks vs. Subroutines The sort routine can be a block of code, enclosed by curly braces {}, or it can be a subroutine defined elsewhere. Which you use is a matter of taste. If the routine is long and complex, a subroutine might be more appropriate, but for simple and short methods, a block is easier. Thus, these two are equivalent: sort {$a $b sort sub numerically { return $a $b; }

Reverse Sort By default, sorting is done from smallest to largest. The simplest way to sort from largest to smallest is to simply reverse $b and $a in the sort routine block: numerical: sort {$b ASCII: sort {$b cmp

Sorting Hash Keys A common problem is to sort the keys of a hash by the values they refer to, for instance to print them in proper order. The trick is to put the keys into an array, then use those keys to access the hash’s values. For example: = keys %hash; = sort {$hash{$a} $hash{$b} Here, each pair of hash keys is taken and substituted into the sort routine, and a sorted list of keys is outputted. it is necessary to put the sorted keys into an array because hash keys are not stored in a fixed order. The array isn’t necessary. This will also work: = sort {$hash{$a} $hash{$b} } keys %hash;

Sorting Array Indices If you have several parallel arrays that you wish to sort simultaneously, you need to create a list of array indices in the sorted order. The procedure is very similar to sorting hash keys. = sort { $arr[$a] $arr[$b] } 0.. $#arr; Here, the indices are accessed through 0.. $#arr. They are then used to compare the actual array elements, and then put into the array. You can then use this array of indices to sort any other arrays in the same order: = = This procedure uses an “array slice”, a list of indices inside the square braces instead of a single index value.

Example You have 3 arrays of student = (57880, 74675, 13892, 20051, = qw(Ahmed Anderson Blackwell Chilson = qw(A C B F B); You want to sort all of them in parallel, by ID = sort {$id[$a] $id[$b]} 0.. $#id; is (2, 4, 3, 0, =

Sorting by Two or More Criteria You want to sort first by one criterion, then resolve ambiguities using a second criterion. For example, sort by last name, then by first name if necessary. To do this, use the “or” operator || between the two comparisons. If the first comparison returns 0 (because they are equal), then do the second comparison. The second is not done if the first comparison returns a TRUE value (i.e. = qw(Coburn Smith Jones Jones = qw(Fred Harold Mary Jane = sort {$last_names[$a] cmp $last_names[$b] || $first_names[$a] cmp $first_names[$b] } 0.. $#last_names; Then use the sorted indices to put both arrays in the proper order.

Grep grep is a useful function taken from Unix. It takes an array as an argument, tests each array element, and returns a list of those elements for which the test is true. grep puts each element of the array into $_ for the test. This is similar to a “foreach” loop. A typical example: return all words in a list containing = qw(the dog went in = grep is (“the”, “there”) This is equivalent (but much shorter than): foreach { if ($_ =~ /th/); } You can use either an expression or a block as the test. Note that you must put a comma after an expression (before the list of elements), but NOT after a block enclosed by curly braces. Thus, this is equivalent to the = grep { /th/ The expression or block must return either a true value or a false value when it is evaluated with $_.

Grep Used to Determine Membership in a List A good use for grep is determining whether a string or number is present in a list. in a scalar context, grep returns the number of times the test expression is true. In a list context, grep returns a list of the array items for which the test expression is true. = qw(cat dog ferret gerbil rabbit); my $animal = ; if (grep $_ = { print “I have a $animal\n”; } else { print “I don’t have a $animal\n”; } grep is being used in a list context: if $animal matches anything on the grep will return a value of 1 or more. If nothing matches, grep returns 0 (false).

Map map is another useful function related to grep. map takes each element of a list or array, substitutes them in turn into $_, and performs some function on them. As with grep, map is simply a shorter way of writing something you could do with a foreach loop. A simple example: adding 3 to each element of an = map {$_ += Just like grep, map can use either an expression (followed by a comma), or a block (no comma). map can return more than one value for each input value. All returned values end up on a single list, however. For example, this function returns a 1, followed by the original value, followed by the square of that value. This function has a real use in multivariate statistics, by the = map { 1, $_, $_ **