Lecture 1 -- 1Computer Science I - Martin Hardwick Searching and sorting rReasons for not using the most efficient algorithm include: l The more efficient.

Slides:



Advertisements
Similar presentations
TWO STEP EQUATIONS 1. SOLVE FOR X 2. DO THE ADDITION STEP FIRST
Advertisements

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 Making our programs more flexible rSo far we have largely programmed using l Arrays of integers l Arrays.
Lecture Computer Science I - Martin Hardwick Strings #include using namespace std; int main () { string word; cout
Lecture Computer Science I - Martin Hardwick Merge Sort Algorithm rMerge sort has two phases. l First it divides the data into smaller and smaller.
0 - 0.
DIVIDING INTEGERS 1. IF THE SIGNS ARE THE SAME THE ANSWER IS POSITIVE 2. IF THE SIGNS ARE DIFFERENT THE ANSWER IS NEGATIVE.
ADDING INTEGERS 1. POS. + POS. = POS. 2. NEG. + NEG. = NEG. 3. POS. + NEG. OR NEG. + POS. SUBTRACT TAKE SIGN OF BIGGER ABSOLUTE VALUE.
SUBTRACTING INTEGERS 1. CHANGE THE SUBTRACTION SIGN TO ADDITION
MULT. INTEGERS 1. IF THE SIGNS ARE THE SAME THE ANSWER IS POSITIVE 2. IF THE SIGNS ARE DIFFERENT THE ANSWER IS NEGATIVE.
Addition Facts
1 CSE1301 Computer Programming: Lecture 27 List Manipulation.
ADTs unsorted List and Sorted List
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.
© S Haughton more than 3?
Past Tense Probe. Past Tense Probe Past Tense Probe – Practice 1.
Addition 1’s to 20.
25 seconds left…...
Test B, 100 Subtraction Facts
Week 1.
Advanced Sorting Methods: Shellsort Shellsort is an extension of insertion sort, which gains speed by allowing exchanges of elements that are far apart.
Topic 16 Sorting Using ADTs to Implement Sorting Algorithms.
Foundations of Data Structures Practical Session #11 Sort properties, Quicksort algorithm.
Lecture Computer Science I - Martin Hardwick Making the bank object oriented rIn upcoming lectures we will be looking at efficiency issues rIn order.
Q-1 University of Washington Computer Programming I Lecture 16: Sorting © 2000 UW CSE.
Sorting A fundamental operation in computer science (many programs need to sort as an intermediate step). Many sorting algorithms have been developed Choose.
 Sort: arrange values into an order  Alphabetical  Ascending numeric  Descending numeric  Does come before or after “%”?  Two algorithms considered.
Sorting Part 2 CS221 – 3/4/09. Announcements Midterm: 3/11 – 15% of your total grade – We will review in class on 3/9 – You can bring one sheet of paper.
Simple Sorting Algorithms
Sorting and Searching. Searching List of numbers (5, 9, 2, 6, 3, 4, 8) Find 3 and tell me where it was.
1 Lecture 21 Introduction to Sorting I Overview  What is Sorting?  Some Useful Array Handling Methods.  Selection Sort and its Implementation.  Brief.
Objectives Learn how to implement the sequential search algorithm Explore how to sort an array using the selection sort algorithm Learn how to implement.
Lecture 14: A Programming Example: Sorting Yoni Fridman 7/24/01 7/24/01.
Algorithm Efficiency and Sorting
Programming Sorting Arrays. COMP104 Lecture 25 / Slide 2 Sorting l To arrange a set of items in sequence. l It was estimated that 25~50% of all computing.
Lecture 08 Sorting. Sorts Many programs will execute more efficiently if the data they process is sorted before processing begins. – We first looked at.
Simple Sorting Algorithms. 2 Bubble sort Compare each element (except the last one) with its neighbor to the right If they are out of order, swap them.
Fall 2013 Instructor: Reza Entezari-Maleki Sharif University of Technology 1 Fundamentals of Programming Session 17 These.
Chapter 16: Searching, Sorting, and the vector Type.
Lecture 6 Sorting Algorithms: Bubble, Selection, and Insertion.
Sorting. Algorithms Sorting reorders the elements in an array or list in either ascending or descending order. Sorting reorders the elements in an array.
Sorting – Insertion and Selection. Sorting Arranging data into ascending or descending order Influences the speed and complexity of algorithms that use.
Fundamentals of Algorithms MCS - 2 Lecture # 15. Bubble Sort.
Sorting List is rearranged into sorted order How is the sorted order determined? – The ItemType is responsible for determining the key to be used in comparison.
3 – SIMPLE SORTING ALGORITHMS
Sorting Algorithms: Selection, Insertion and Bubble.
1 Chapter 13-2 Applied Arrays: Lists and Strings Dale/Weems.
Q-1 University of Washington Computer Programming I Lecture 16: Sorting © 2000 UW CSE.
Computer Science 1620 Sorting. cases exist where we would like our data to be in ascending (descending order) binary searching printing purposes selection.
Chapter 16: Searching, Sorting, and the vector Type.
1 compares each element of the array with the search key. works well for small arrays or for unsorted arrays works for any table slow can put more commonly.
CS212: Data Structures and Algorithms
Sorting Why? Displaying in order Faster Searching Categories Internal
Lecture 14 Searching and Sorting Richard Gesick.
Introduction to Search Algorithms
Simple Sorting Algorithms
Design and Analysis of Algorithms
Topic 14 Searching and Simple Sorts
Objectives At the end of the class, students are expected to be able to do the following: Understand the purpose of sorting technique as operations on.
Selection Sort Sorted Unsorted Swap
Selection Sort – an array sorting algorithm
Lecture 11 Searching and Sorting Richard Gesick.
Searching and Sorting 1-D Arrays
Intro to Sorting Sorting
Topic 14 Searching and Simple Sorts
Sorting "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 Sorting Hat, Harry Potter.
Topic 24 sorting and searching arrays
Searching.
Simple Sorting Algorithms
Simple Sorting Algorithms
Presentation transcript:

Lecture Computer Science I - Martin Hardwick Searching and sorting rReasons for not using the most efficient algorithm include: l The more efficient algorithm is much more complicated. Therefore, it is harder to maintain and debug. l The more efficient algorithm requires another part of the system to prepare data and preparing this data takes a long time. rFor example, binary search requires sorted data l As we shall see the sorting algorithms are relatively complicated. l And they are slow – the best algorithms are O (n log n). l Making searching faster by going from O (n) to O (log n) is not worth it if the price is having to use a new algorithm that is O(n log n). rHowever, society has organized itself so that sorting does not have to be used too often l For example, banks only sort their data once per day

Lecture Computer Science I - Martin Hardwick Creating a Sorted List void banking::Insert( /* in */ acct item ) // Inserts into a list of bank accounts // Data is vector { int index = data.size() - 1; data.push_back (item); while (index >= 0 && item.get_num() < data[index].get_num()) { data[index+1] = data[index]; index--; } data[index+1] = item; // Insert item } rAs we have seen, using the Insert() operation for the SortedList class repeatedly allows us to create a sorted list. l but is this efficient? rIn the worst case, each call to Insert() moves the entire list one slot. l first call moves 0 items l second call moves 1 item l third call moves 2 items l... l Nth call moves N-1 items. rFor a list of length N, this requires: l … + (n-1) moves l =

Lecture Computer Science I - Martin Hardwick Discussion rRepeated use of the Insert() operation sorts a list using O(n 2 ) moves and O(n 2 ) comparisons. l each move is preceded by a comparison between variable item and the list element to be moved rWe can do better than repeated use of the Insert() operation, however. rThere is a simple sorting algorithm that uses O(n 2 ) comparisons but only O(n) moves. l it is called Selection Sort

Lecture Computer Science I - Martin Hardwick Selection Sort (1) #include using namespace std; void banking::selection(vector &list) //PURPOSE: sort list into ascending // order using selection sort //POSTCONDITIONS: reorders list // into ascending order { // size of list int length = list.size(); // position of min number int minLoc; // top of sorted part of list int top; rGiven a list of numbers, we want to sort the list into ascending order. rWe will do the sorting in a function that can be moved to any program that needs to sort a list.

Lecture Computer Science I - Martin Hardwick Selection Sort Algorithm rAt any point during the algorithm, the first part of the list is sorted and the last part is unsorted. l initially the first part is empty and the last part is the entire list rSearch the unsorted part of the list for the smallest number. rSwap this smallest number to beginning of unsorted part of the list. rRepeat this process until the list is sorted sortedunsorted k minLoc k k k k k k k k k k k k k k temp top 520 k minLoc 20 sortedunsorted

Lecture Computer Science I - Martin Hardwick Selection Sort (2) // swap numbers in list int temp; // loop variable intk; // loop to sort list for (top=0; top<=length-2; top++) { // find smallest number in unsorted // part of the list minLoc = top; for (k=top+1; k<=length-1; k++) { if (list[k] < list[minLoc]) { minLoc = k; } rIn a list of length n, once n-1 numbers are in their final positions, the list is sorted. l by default, the remaining number must be in the correct position rStart by assuming that the first number in the unsorted part of the list is the smallest remaining number. l search the rest of the unsorted list for something smaller l remember where the smallest number is

Lecture Computer Science I - Martin Hardwick Selection Sort (3) // swap smallest number // into its final position in // the sorted list temp = list[top]; list[top] = list[minLoc]; list[minLoc] = temp; } rThe program swaps two elements of the list. l the smallest remaining number and the first number in the unsorted part of the list rSwapping requires an extra variable (named temp in this case) to temporarily hold the value of one of the variables being swapped. rThe sorted part of the list is now one element longer. l the unsorted part is one element shorter

Lecture Computer Science I - Martin Hardwick Selection Sort (3) int main () //PURPOSE: test selection function //PRECONDITIONS: file list.txt in // project folder //POSTCONDITIONS: rets 0 if success { vector list; int k; // loop variable int tmp; // tmp variable ifstream listfile; // file with list // read the numbers into the list // and display them on the screen listfile.open("list.txt"); listfile >> tmp; list.push_back (tmp); cout << "Original List:" << endl; while (!listfile.eof()) { cout << tmp << "\t"; listfile >> tmp; list.push_back (tmp); } rRead the list of numbers from a file named list.txt. rDisplay the list before sorting.

Lecture Computer Science I - Martin Hardwick Selection Sort (4) // sort the list selection(list); // display the sorted list cout << endl << endl << "Sorted List:" << endl; for (k=0; k<list.size(); k++) { cout << list[k] << "\t"; } cout << endl << endl; return 0; } rFunction selection() sorts the list. l remember that a vector must be passed by reference rAfter sorting, the list is displayed again so that the new sorted order can be seen.

Lecture Computer Science I - Martin Hardwick Program Results

Lecture Computer Science I - Martin Hardwick Performance Of Selection Sort rThe selection sort function has nested for loops as follows: rThe outer loop is executed n-1 times, where n is the length of the list. rThe inner loop executes: n-1, n-2, n-3,..., 2, 1 times on successive iterations of the outer loop, respectively. l this is an average of about n/2 times for large n rThus, the comparison inside the inner loop is made about (n-1)x(n/2) = 1/2(n 2 -n) times. rTherefore, selection sort is an O(n 2 ) algorithm because of the number of comparisons that it does. rHowever, it does O(n) moves, making it more efficient that repeated calls to the Insert() operator for the SortedList class. for (top=0; top<=length-2; top++) {... for (k=top+1; k<=length-1; k++) { comparison of list elements }

Lecture Computer Science I - Martin Hardwick What Does This Mean? rThe most efficient sorting algorithms can be shown to be O(nlog 2 n), where n is the size of the list to sort. rAs can be seen in the graph O(nlog 2 n) is much better than O(n 2 ) when n gets large. n 2 nlog 2 n n

Lecture Computer Science I - Martin Hardwick More efficient sorting rThe best sorting algorithms are O (n log n) rThese algorithms require a programming technique called recursion rA recursive function is one that calls itself rA recursive function must have at least two parts l A part that solves a simple case of the problem without recursion l A part that makes the problem simpler and then uses recursion rHere is a simple recursive function rMore on recursion next time int factorial (int val) { if (val == 1)// simple part return 1; else// simplification part return (val * factorial (val-1)); }