Lecture 1 -- 1Computer Science I - Martin Hardwick Merge Sort Algorithm rMerge sort has two phases. l First it divides the data into smaller and smaller.

Slides:



Advertisements
Similar presentations
Topic Reviews For Unit ET156 – Introduction to C Programming Topic Reviews For Unit
Advertisements

Recursion.
Lecture Computer Science I - Martin Hardwick Searching and sorting rReasons for not using the most efficient algorithm include: l The more efficient.
Lecture Computer Science I - Martin Hardwick Bubble Sort bool bubble_once( vector &list, int top) // Perform one bubble iteration on a list { bool.
Lecture Computer Science I - Martin Hardwick Streams In C++ rA stream is a sequence that you either read from or write to. l example – cin is a stream.
Lecture Computer Science I - Martin Hardwick Making our programs more flexible rSo far we have largely programmed using l Arrays of integers l Arrays.
Copyright © 2006 The McGraw-Hill Companies, Inc. Programming Languages 2nd edition Tucker and Noonan Chapter 11 Memory Management C makes it easy to shoot.
Outline lecture Revise arrays Entering into an array
Chapter 7: Arrays In this chapter, you will learn about
Memory Management Chapter FourteenModern Programming Languages, 2nd ed.1.
Towers of Hanoi Move n (4) disks from pole A to pole C such that a disk is never put on a smaller disk A BC ABC.
Databasteknik Databaser och bioinformatik Data structures and Indexing (II) Fang Wei-Kleiner.
Pointers and Data Structures 1 Yinzhi Cao Modified from slides made by Prof Goce Trajcevski.
Chapter 17 Linked Lists.
DATA STRUCTURES USING C++ Chapter 5
11 Data Structures Foundations of Computer Science ã Cengage Learning.
Data Structures Using C++
Topic 14 Searching and Simple Sorts "There's nothing in your head the sorting hat can't see. So try me on and I will tell you where you ought to be." -The.
FIFO Queues CSE 2320 – Algorithms and Data Structures Vassilis Athitsos University of Texas at Arlington 1.
Module 10: Virtual Memory
Chapter 10: Virtual Memory
SEG4110 – Advanced Software Design and Reengineering TOPIC J C++ Standard Template Library.
ITEC200 Week10 Sorting. pdp 2 Learning Objectives – Week10 Sorting (Chapter10) By working through this chapter, students should: Learn.
Part IV: Memory Management
Topic 16 Sorting Using ADTs to Implement Sorting Algorithms.
1 Arrays and Strings Chapter 9 2 "All students to receive arrays!" reports Dr. Austin. Declaring arrays scores :
Dynamic Memory Allocation in C.  What is Memory What is Memory  Memory Allocation in C Memory Allocation in C  Difference b\w static memory allocation.
12-Apr-15 Analysis of Algorithms. 2 Time and space To analyze an algorithm means: developing a formula for predicting how fast an algorithm is, based.
Lecture 10: Heap Management CS 540 GMU Spring 2009.
COSC 2006 Data Structures I Recursion III
Chapter 8 Runtime Support. How program structures are implemented in a computer memory? The evolution of programming language design has led to the creation.
Sorting Chapter Sorting Consider list x 1, x 2, x 3, … x n We seek to arrange the elements of the list in order –Ascending or descending Some O(n.
An Array-Based Implementation of the ADT List public class ListArrayBased implements ListInterface { private static final int MAX_LIST = 50; private Object.
Lesson 19 Recursion CS1 -- John Cole1. Recursion 1. (n) The act of cursing again. 2. see recursion 3. The concept of functions which can call themselves.
1 CSE 380 Computer Operating Systems Instructor: Insup Lee University of Pennsylvania, Fall 2002 Lecture Note: Memory Management.
Scott Grissom, copyright 2004 Chapter 5 Slide 1 Analysis of Algorithms (Ch 5) Chapter 5 focuses on: algorithm analysis searching algorithms sorting algorithms.
Run-Time Storage Organization
Sorting Chapter 10.
Pointers and Dynamic Variables. Objectives on completion of this topic, students should be able to: Correctly allocate data dynamically * Use the new.
Sorting Chapter 10. Chapter 10: Sorting2 Chapter Objectives To learn how to use the standard sorting methods in the Java API To learn how to implement.
Ordered Arrays An array is ordered if the elements are in ascending or descending order. The array may be ordered numerically or alphabetically (which.
External Sorting Problem: Sorting data sets too large to fit into main memory. –Assume data are stored on disk drive. To sort, portions of the data must.
CS3012: Formal Languages and Compilers The Runtime Environment After the analysis phases are complete, the compiler must generate executable code. The.
Dynamic Memory Allocation Questions answered in this lecture: When is a stack appropriate? When is a heap? What are best-fit, first-fit, worst-fit, and.
Recursion Textbook chapter Recursive Function Call a recursive call is a function call in which the called function is the same as the one making.
Order Statistics. Order statistics Given an input of n values and an integer i, we wish to find the i’th largest value. There are i-1 elements smaller.
Sorting Chapter 10. Chapter Objectives  To learn how to use the standard sorting methods in the Java API  To learn how to implement the following sorting.
Adapted from instructor resource slides Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All.
External Storage Primary Storage : Main Memory (RAM). Secondary Storage: Peripheral Devices –Disk Drives –Tape Drives Secondary storage is CHEAP. Secondary.
Stacks. A stack is a data structure that holds a sequence of elements and stores and retrieves items in a last-in first- out manner (LIFO). This means.
1 C++ Classes and Data Structures Jeffrey S. Childs Chapter 4 Pointers and Dynamic Arrays Jeffrey S. Childs Clarion University of PA © 2008, Prentice Hall.
Sorting Chapter Sorting Consider list x 1, x 2, x 3, … x n We seek to arrange the elements of the list in order –Ascending or descending Some O(n.
Run-Time Storage Organization Compiler Design Lecture (03/23/98) Computer Science Rensselaer Polytechnic.
+ Dynamic memory allocation. + Introduction We often face situations in programming where the data is dynamics in nature. Consider a list of customers.
Memory Management in Java Computer Science 3 Gerb Objective: Understand references to composite types in Java.
COMP091 – Operating Systems 1 Memory Management. Memory Management Terms Physical address –Actual address as seen by memory unit Logical address –Address.
Computer Science Department Data Structure and Algorithms Lecture 3 Stacks.
Prof. U V THETE Dept. of Computer Science YMA
Data Structures Interview / VIVA Questions and Answers
CS 153: Concepts of Compiler Design November 28 Class Meeting
Pointers and Dynamic Variables
Arrays and Linked Lists
Algorithm An algorithm is a finite set of steps required to solve a problem. An algorithm must have following properties: Input: An algorithm must have.
Lecture 11 Memory Richard Gesick.
Sorting Chapter 8 CS 225.
Sub-Quadratic Sorting Algorithms
Dynamic Memory And Objects
Intro to Computer Science CS1510 Dr. Sarah Diesburg
Sorting Chapter 10.
Comp 208 Computers in Engineering Yi Lin Fall, 2005
Presentation transcript:

Lecture Computer Science I - Martin Hardwick Merge Sort Algorithm rMerge sort has two phases. l First it divides the data into smaller and smaller lists until they are size 2 or 1 l Second as it returns it merges all the lists using a merge algorithm rConsider the following data set. – l The first two sub lists for merging will be –45 78 –20 34 l After merge – l The next two sub-lists are –15 18 –10 96 l After merge – l Final merge yields –

Lecture Computer Science I - Martin Hardwick Merge vector merge( vector list1, vector list2) // Merge two sorted lists { vector result; int i1 = 0; int i2 = 0; while (i1 < list1.size() || i2 < list2.size()) { if (i1 < list1.size() && i2 < list2.size()) { if (list1[i1] < list2[i2]) result.push_back (list1[i1++]); else result.push_back (list2[i2++]); } else { while (i1 < list1.size()) result.push_back (list1[i1++]); while (i2 < list2.size()) result.push_back (list2[i2++]); } return result; } rThis algorithm picks the smallest item from each list. rWhen it reaches the end of one list it then fills in the remaining items from the other list. rConsider l List1: l List2: rList 1 will be consumed first l Result: l I1 = 4 l I2 = 2 rWe then add 80 and 90 from list 2 l Result: l I1 = 4 l I2 = 4

Lecture Computer Science I - Martin Hardwick Data management issues rThe given algorithm is not very efficient. l It adds too many items to too many vectors using push_back. l The system may run out of space and have to garbage collect rA more efficient approach is to define the space needed at the beginning of the program l Either –Create a vector with a specific size vector result (10000); –Use ordinary arrays with enough size int result [1000]; rAnother issue for the largest test (128,000) items is running out of memory in your program. To fix this: l Goto Project/Properties l Select Linker/System l Set the stack sizes to 1,000,000,000

Lecture Computer Science I - Martin Hardwick Memory management rThe memory is divided into three areas rStatic area (not shown) l This area is of fixed size l It stores the program code and any static (global) variables rStack area l This area stores the stack frames of all the currently executing functions l It needs to be big enough for all of the local data for all the functions rHeap area l This area stores all the data whose size cannot be predicted Call stack Frame Call stack Frame Call stack Frame Call stack Frame Call stack Frame gap top

Lecture Computer Science I - Martin Hardwick Memory management rIf the heap grows too large then it will collide with the stack and the system will run out of memory rThe heap contains random items of random size some of which are no longer used l A garbage collector can go and find these unused locations (pass 1) l Compress all the space by squeezing out the gaps (pass 2) l Leaving new space at the top of the heap rHowever, running the garbage collector is very expensive l We can help by not wasting memory l By telling the system when something is going to grow big vector result (10000) l So that the system does not waste space by first creating a small vector, then a middle size copy, then a large, then a very large, then an enormous copy.

Lecture Computer Science I - Martin Hardwick Memory management rA vector object is divided into two components rThe header containing fixed size information l Current number of elements l Pointer to data elements l Stored on the stack rData elements l The data items in sequence stored in the heap rMore on this CS 2 l How to make and use pointers l How to get your own data on the heap. Vector V1 Header elements gap top Vector V2 Header elements Data elements for v1

Lecture Computer Science I - Martin Hardwick Merge made more efficient vector merge( vector list1, vector list2) // Merge two sorted lists { vector result (list1.size() + list2.size()); int i1 = 0; int i2 = 0; int resi = 0; while (i1 < list1.size() || i2 < list2.size()) { if (i1 < list1.size() && i2 < list2.size()) { if (list1[i1] < list2[i2]) result[resi++] = list1[i1++]; else result[resi++] = list2[i2++]; } else { while (i1 < list1.size()) result[resi++] = list1[i1++]; while (i2 < list2.size()) result[resi++] = list2[i2++]; } return result; } rThis algorithm sets a size for the new list. rTherefore, it does not need to use push_back rStill slow compared to array solution however. rArrays always use a big block of contiguous memory. rPaging is not such an issue. r(Paging occurs when the OS has to get data for your program from the disk)

Lecture Computer Science I - Martin Hardwick Operator Overloading bool operator >(acct a, acct b) { return a.get_num() > b.get_num(); } ostream& operator<< (ostream &s, acct a) { os << Name: << a.get_name(); os << Balance: << a.get_bal(); return os; } acct operator + (acct a, acct b) { return acct (a.get_num(), a.get_name(), a.get_bal() + b.get_bal()); } rRemember the bank account example. rWe can enrich this example by using operator overloading rThe code on the left defines l The meaning of > for bank accounts l A special version of << for bank accounts l A plus function for bank accounts that returns the value of a with bs balance added

Lecture Computer Science I - Martin Hardwick Operator overloading and sort class acct {// bank account data private: intnum;// account number stringname;// owner of account doublebalance;// balance in account public: acct (); acct (int anum, string aname, double abal); double get_bal (); string get_name(); int get_num (); void put_num (int num); void put_name (string name); void put_bal (double bal); bool is_bankrupt(); bool operator<(acct b); bool operator>(acct b); }; rThere is a sort function in that can be used to sort a vector of any type of data. rAll we have to do is define the > and < operators for this data

Lecture Computer Science I - Martin Hardwick Implementation bool acct::operator< (acct b) { return get_name() < b.get_name(); } bool acct::operator> (acct b) { return get_name() > b.get_name(); } rIn the implementation we give a meaning to the > and < operators. rIn this case we are defining them using the alphabetic order of the names. rThese are object functions so get_name() returns the name of this object.

Lecture Computer Science I - Martin Hardwick Usage else if (command == "sort") {// LIST COMMAND for (loc=0; loc < my_bank.size () - 1; loc++) { if (my_bank.get (loc) > my_bank.get (loc + 1)) cout << "Bank is out of order at location " << loc << endl; } vector temp = my_bank.get_all(); sort (temp.begin(), temp.end()); my_bank.put_all (temp); cout << Sorted List of accounts:" << endl; for (loc=0; loc < my_bank.size (); loc++) { account = my_bank.get (loc); cout << "Account: " << account.get_num() << \tOwner: " << account.get_name() << \tBalance: " << account.get_bal() << endl; } rYou must include at the top of your program. rThis code tests for unsorted data. rThen it does a sort rThen it prints the new data rAfter the sort the accounts will be sorted by name! Not by number. l Do not try using the insert functionality in the bank account example after doing this sort l A better solution will put the sort into a member function on the bank