Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS1010: Programming Methodology

Similar presentations


Presentation on theme: "CS1010: Programming Methodology"— Presentation transcript:

1 CS1010: Programming Methodology http://www.comp.nus.edu.sg/~cs1010/

2 Week 10: Searching and Sorting
CS1010 Programming Methodology Week 10: Searching and Sorting Objectives: Understand the basic searching algorithms and sorting algorithms Introduce the concept of complexity analysis (informally) Implement the searching and sorting algorithms using arrays. Reference: Chapter 6 Numeric Arrays Lesson 6.6 Bubble Sort, Exchange Maximum Sort CS1010 (AY2012/3 Semester 1)

3 CS1010 Programming Methodology
Week 10: Outline (1/2) Week 9 Exercise #3 Arrow Program Overall Introduction Introduction to Searching Linear Search Demo #1 Performance Exercise #1: Compatible Teammate Binary Search Searching Timing given here are for your own reference only. Week 9 Exercise #3 Arrow Program (10 minutes) Overall Introduction (3 minutes) Introduction to Searching (5 minutes) Linear Search (10) Exercise #1: Compatible teammate (22)  Break after this Binary Search (10) Introduction to Sorting (5) Selection Sort (15) Exercise #2: Points and Lines (20)  Break after this Bubble Sort (15) More Sorting Algorithms (2) Animated Sorting Algorithms (5) Exercise #3: Module Sorting (take-home) (3) CS1010 (AY2012/3 Semester 1)

4 CS1010 Programming Methodology
Week 10: Outline (2/2) Introduction to Sorting Selection Sort Demo #2 Performance Exercise #2: Points and Lines Bubble Sort Demo #3 More Sorting Algorithms Animated Sorting Algorithms Exercise #3: Module Sorting (take-home) SORTing Timing given here are for your own reference only. Week 9 Exercise #3 Arrow Program (10 minutes) Overall Introduction (3 minutes) Introduction to Searching (5 minutes) Linear Search (10) Exercise #1: Compatible teammate (22)  Break after this Binary Search (10) Introduction to Sorting (5) Selection Sort (15) Exercise #2: Points and Lines (20)  Break after this Bubble Sort (15) More Sorting Algorithms (2) Animated Sorting Algorithms (5) Exercise #3: Module Sorting (take-home) (3) CS1010 (AY2012/3 Semester 1)

5 1. Week 9 Ex #3: Arrow Program (1/2)
CS1010 Programming Methodology 1. Week 9 Ex #3: Arrow Program (1/2) Write a program Week9_Arrow.c to randomly select a student to answer question. The program reads in a list of names and use rand() to randomly select one of the names. When a name is selected, the program will print out the first name, followed by the last name. For example, if the selected name is Tan Mei Ling. The program will print: Mei Tan, would you please answer the question? You may assume that each name contains at most 30 characters, and there are at most 12 names. Program is Week19_Arrow.c (not given to students CS1010 (AY2012/3 Semester 1)

6 1. Week 9 Ex #3: Arrow Program (2/2)
CS1010 Programming Methodology 1. Week 9 Ex #3: Arrow Program (2/2) A sample run: Enter names: Khoo Siau Cheng Hsu Wynne Lee Mong Li Aaron Tan Zhou Lifeng Zhao Jin Name selected: Siau Khoo, would you please answer the question? CS1010 (AY2012/3 Semester 1)

7 while (fgets(nameList[i], NAME_LENGTH+1, stdin) != NULL) {
printf("Enter names (terminate with ctrl-d):\n"); while (fgets(nameList[i], NAME_LENGTH+1, stdin) != NULL) { if (i++ >= GRP_SIZE) break; } srand(time(NULL)); index = (rand() / (double) RAND_MAX) * (i - 1); //Find the last and first name strcpy(lastname, strtok(nameList[index], " ")); strcpy(firstname, strtok(NULL, " ")); printf("Name selected:\n"); printf("%s %s, would you please answer the question?\n“, firstname, lastname); CS1010 (AY2012/3 Semester 1)

8 CS1010 Programming Methodology
2. Overall Introduction You have accumulated quite a bit of basic programming experience by now. Today, we will study some simple yet useful classical algorithms which find their place in many CS applications Searching for some data amid very large collection of data Sorting very large collection of data according to some order How large is the collection of data that we are considering? We will begin with an algorithm (idea), and show how the algorithm is transformed into a C program (implementation). This brings back (reminds you) our very first lecture: the importance of beginning with an algorithm. CS1010 (AY2012/3 Semester 1)

9 3. Introduction to Searching (1/2)
CS1010 Programming Methodology 3. Introduction to Searching (1/2) Searching is a common task that we carry out without much thought everyday. Searching for a location in a map Searching for the contact of a particular person Searching for a nice picture for your project report Searching for a research paper required in your course. In this lecture, you will learn how to search for an item (sometimes called a search key) in an array. CS1010 (AY2012/3 Semester 1)

10 3. Introduction to Searching (2/2)
CS1010 Programming Methodology 3. Introduction to Searching (2/2) Problem statement: Given a list (collection of data) and a search key X, return the position of X in the list if it exists. For simplicity, we shall assume there are no duplicate values in the list. Our learning objectives: Two methods of finding an item with the search key X Linear/Sequential Search Binary Search Quantitative assessment of the quality of the method CS1010 (AY2012/3 Semester 1)

11 3. Introduction to Searching (2/2)
CS1010 Programming Methodology 3. Introduction to Searching (2/2) Problem statement: Given a list (collection of data) and a search key X, return the position of X in the list if it exists. For simplicity, we shall assume there are no duplicate values in the list. We will count the number of comparisons the algorithms make to analyze their performance. The ideal searching algorithm will make the least possible number of comparisons to locate the desired data. We will introduce worst-case scenario. (This topic is called analysis of algorithms, which will be formally introduced in CS1020. Here, we will give an informal introduction just for an appreciation.) CS1010 (AY2012/3 Semester 1)

12 4. Linear Search Also known as Sequential Search
CS1010 Programming Methodology 4. Linear Search Also known as Sequential Search Idea: Search the list from one end to the other end in linear progression. Algorithm Example: Search for 24 in this list // Search for key in list A with n items linear_search(A, n, key) { for i = 0 to n-1 if Ai is key then report i } no no no no yes! You can ask students what the algorithm should report if key is not found. Question: What to report if key is not found? Aim for a clean design CS1010 (AY2012/3 Semester 1) ©The McGraw-Hill Companies, Inc. 12

13 CS1010 Programming Methodology
4. Demo #1: Linear Search If the list is an array, how would you implement the Linear Search algorithm? // To search for key in arr using linear search // Return index if found; otherwise return -1 int linearSearch(int arr[], int size, int key) { int i; for (i=0; i<size; i++) if (key == arr[i]) return i; return -1; } See linear_search.c for full program Program is linear_search.c The function will return the position of the first location of the key in the array. Should also show the main() function in class to see how to make use of the return statement of linearSearch(). Question: What if array contains duplicate values of the key? CS1010 (AY2012/3 Semester 1) ©The McGraw-Hill Companies, Inc. 13

14 4. Linear Search: Performance Analysis
CS1010 Programming Methodology 4. Linear Search: Performance Analysis We use the number of comparisons here as a rough measurement. Analysis is usually done for best case, average case, and worst case. We will focus on the worst case. For an array with n elements, in the worst case, What is the number of comparisons in our linear search algorithm? Under what circumstances do we encounter the worst case? n comparisons n comparisons in the worst case. Worst case happens when (a) the key is not found, or (b) the key is found at the last element of the array. Not found Found at last element CS1010 (AY2012/3 Semester 1) ©The McGraw-Hill Companies, Inc. 14

15 5. Exercise #1: Compatible Teammate (1/4)
CS1010 Programming Methodology 5. Exercise #1: Compatible Teammate (1/4) Given three arrays: The first array contains the players’ names. The second array stores the players’ ages corresponding to the entries in the first array. The third array contains the gender information for each player corresponding to the entries in the first array. Your task is to accept as input a player’s name and find a compatible teammate for this player – a teammate who is of the same age but opposite sex. Analysis: Inputs: char player_name[STR_LENGTH+1]; char names[MAX_PLAYER][STR_LENGTH+1]; int ages[MAX_PLAYER]; char genders[MAX_PLAYER]; CS1010 (AY2012/3 Semester 1)

16 5. Exercise #1: Compatible Teammate (2/4)
CS1010 Programming Methodology 5. Exercise #1: Compatible Teammate (2/4) Sample run: Enter 5 players’ info: Alvin 23 M Byron 21 M May 19 F June 21 F Jupiter 22 M The list of players are: Name Age Gender Alvin M Byron M May F June F Jupiter M Enter a player's name: Byron Byron’s compatible teammate is June. Enter a player's name: Alvin Sorry, we cannot find a teammate for Alvin! or Enter a player's name: John No such player John. or Download the incomplete program Complete the search_teammate() function. CS1010 (AY2012/3 Semester 1)

17 5. Exercise #1: Compatible Teammate (3/4)
CS1010 Programming Methodology 5. Exercise #1: Compatible Teammate (3/4) int main(void) { char names[MAX_PLAYER][STR_LENGTH+1]; int ages[MAX_PLAYER]; char genders[MAX_PLAYER]; char player_name[STR_LENGTH+1]; int i, result; printf("Enter %d players' info:\n", MAX_PLAYER); for (i=0; i<MAX_PLAYER; i++) scanf("%s %d %c", names[i], &ages[i], &genders[i]); printf("The list of players are:\n"); printf("Name\tAge\tGender\n"); printf("%s\t%d\t%c\n", names[i], ages[i], genders[i]); printf("Enter a player's name: "); scanf("%s", player_name); result = search_teammate(names, ages, genders, MAX_PLAYER, player_name); if (result == -2) printf("No such player %s.\n", player_name); else if (result == -1) printf("Sorry, we cannot find a teammate for %s!\n", player_name); else printf("%s's compatible teammate is %s.\n", player_name, names[result]); return 0; } Week10_TeamMate.c Program given to students is Week10_Teammate.c Complete program is Week10_Teammate_Complete.c Bring students’ attention to the values -2 and -1 returned by search_teammate() function. This is some sort of information coding. Of course, we could have written a separate function to check if player exists, and if so, call search_teammate() to search for the compatible teammate. What if there are more than one compatible teammate? Our solution returns the index of the first one found. CS1010 (AY2012/3 Semester 1)

18 5. Exercise #1: Compatible Teammate (4/4)
CS1010 Programming Methodology 5. Exercise #1: Compatible Teammate (4/4) // Search for a player's compatible teammate // Return index in array if compatible teammate found, or // if compatible teammate not found, or // if player not found int search_teammate(char names[][STR_LENGTH+1], int ages[], char genders[], int size, char player_name[]) { int i, player_index = -1; // First, check that the player_name appears in the names array for (i=0; i<size; i++) { if (strcmp(player_name, names[i]) == 0) player_index = i; } if (player_index == -1) return -2; // no such student in array if ((ages[i] == ages[player_index]) && (genders[i] != genders[player_index])) return i; return -1; // cannot find compatible teammate This slide is blank in the students’ version, except for the function header. Give the students enough time (20 minutes) to work on the function. After that, you can either discuss a student’s function, or explain this to the class. CS1010 (AY2012/3 Semester 1)

19 CS1010 Programming Methodology
6. Binary Search (1/6) You are going to witness a radically different approach, one that has become the basis of many well-known algorithms in Computer Science! The idea is simple and fantastic, but when applied on the searching problem, it has this pre-condition that the list must be sorted before-hand. How the data is organized (in this case, sorted) usually affects how we choose/design an algorithm to access them. In other words, sometimes (actually, very often) we seek out new way to organize the data so that we can process them more efficiency. CS1010 (AY2012/3 Semester 1) ©The McGraw-Hill Companies, Inc. 19

20 6. Binary Search (2/6) The Binary Search algorithm
CS1010 Programming Methodology 6. Binary Search (2/6) The Binary Search algorithm Look for the key in the middle position of the list. Either of the following 2 cases happens: If the key is smaller than the middle element, then “discard” the right half of the list and repeat the process. If the key is greater than the middle element, then “discard” the left half of the list and repeat the process. Terminating condition: when the key is found, or when all elements have been “discarded”. CS1010 (AY2012/3 Semester 1) ©The McGraw-Hill Companies, Inc. 20

21 6. Binary Search (3/6) Example: Search key = 23 5 12 17 23 38 44 77 84
CS1010 Programming Methodology 6. Binary Search (3/6) Example: Search key = 23 5 12 17 23 38 44 77 84 90 [0] [1] [2] [3] [4] [5] [6] [7] [8] array 1. low = 0, high = 8, mid = (0+8)/2 = 4 Found! Return 3 2. low = 0, high = 3, mid = (0+3)/2 = 1 3. low = 2, high = 3, mid = (2+3)/2 = 2 4. low = 3, high = 3, mid = (3+3)/2 = 3 CS1010 (AY2012/3 Semester 1) ©The McGraw-Hill Companies, Inc. 21

22 CS1010 Programming Methodology
6. Binary Search (4/6) In binary search, each step eliminates the problem size (array size) by half. The problem size gets reduced to 1 very quickly! (see next slide) This is a simple yet powerful strategy, of halving the solution space in each step Which lab exercise employs similar strategy? Such strategy, a special case of divide-and-conquer paradigm, can be naturally implemented using recursion (a topic we will cover next week) But for today, we will stick to iteration (loop) Lab 3 Ex2 Bisection Method CS1010 (AY2012/3 Semester 1) ©The McGraw-Hill Companies, Inc. 22

23 6. Binary Search (5/6): Performance
CS1010 Programming Methodology 6. Binary Search (5/6): Performance Worst-case analysis Array size n Linear Search (n comparisons) Binary search (log2 n comparisons) 100 7 1,000 10 10,000 14 100,000 ? 1,000,000 109 17 20 30 CS1010 (AY2012/3 Semester 1) ©The McGraw-Hill Companies, Inc. 23

24 6. Binary Search (6/6): Code
CS1010 Programming Methodology 6. Binary Search (6/6): Code // To search for key in sorted arr using binary search // Return index if found; otherwise return -1 int binarySearch(int arr[], int size, int key) { int low = 0, high = size – 1, mid = (low + high)/2; } binary_search.c while ((low <= high) && (arr[mid] != key)) { if (key < arr[mid]) high = mid - 1; else low = mid + 1; mid = (low + high)/2; } if (low > high) return -1; else return mid; Program binary_search.c is given to students. Complete program is binary_search_complete.c (not given to students) I want students to think about the code before I show it to them. By now, given the algorithm, they should be able to write out the code. CS1010 (AY2012/3 Semester 1) ©The McGraw-Hill Companies, Inc. 24

25 7. Introduction to Sorting (1/2)
CS1010 Programming Methodology 7. Introduction to Sorting (1/2) Sorting is any process of arranging items in some sequence and/or in different sets – Wikipedia. Sorting is important because once a set of items is sorted, many problems (such as searching) become easy. Searching can be speeded up. Determining whether the items in a set are all unique. Finding the median item in the set. etc. CS1010 (AY2012/3 Semester 1) ©The McGraw-Hill Companies, Inc. 25

26 7. Introduction to Sorting (2/2)
CS1010 Programming Methodology 7. Introduction to Sorting (2/2) Problem statement: Given a list of n items, arrange the items into ascending order. We will implement the list as an integer array. We will introduce two basic sort algorithms. We will count the number of comparisons the algorithms make to analyze their performance. The ideal sorting algorithm will make the least possible number of comparisons to arrange data in a designated order. We will compare the algorithms by analyzing their worst- case performance. CS1010 (AY2012/3 Semester 1) ©The McGraw-Hill Companies, Inc. 26

27 8. Selection Sort (1/3) Selection Sort algorithm
CS1010 Programming Methodology 8. Selection Sort (1/3) Selection Sort algorithm Step 1: Find the smallest element in the list (find_min) Step 2: Swap this smallest element with the element in the first position. (Now, the smallest element is in the right place.) Step 3: Repeat steps 1 and 2 with the list having one fewer element (i.e. the smallest element just found and placed is “discarded” from further processing). CS1010 (AY2012/3 Semester 1) ©The McGraw-Hill Companies, Inc. 27

28 8. Selection Sort (2/3) n = 9 23 17 5 90 12 44 38 84 77 1st pass: 5 17
CS1010 Programming Methodology 8. Selection Sort (2/3) n = 9 first min 23 17 5 90 12 44 38 84 77 [0] [1] [2] [3] [4] [5] [6] [7] [8] array 1st pass: first min 5 17 23 90 12 44 38 84 77 2nd pass: first min 5 12 23 90 17 44 38 84 77 3rd pass: first min 5 12 17 90 23 44 38 84 77 4th pass: CS1010 (AY2012/3 Semester 1) ©The McGraw-Hill Companies, Inc. 28

29 CS1010 Programming Methodology
8. Selection Sort (3/3) Q: How many passes for an array with n elements? n = 9 first min n – 1 passes 5 12 17 23 90 44 38 84 77 5th pass: first min 5 12 17 23 38 44 90 84 77 6th pass: first min 5 12 17 23 38 44 90 84 77 7th pass: first min 5 12 17 23 38 44 77 84 90 8th pass: 5 12 17 23 38 44 77 84 90 Final array: CS1010 (AY2012/3 Semester 1) ©The McGraw-Hill Companies, Inc. 29

30 8. Demo #2: Selection Sort See selection_sort.c for full program
CS1010 Programming Methodology 8. Demo #2: Selection Sort // To sort arr in increasing order void selectionSort(int arr[], int size) { int i, start, min_index, temp; for (start = 0; start < size-1; start++) { // each iteration of the for loop is one pass // find the index of minimum element min_index = start; for (i = start+1; i < size; i++) if (arr[i] < arr[min_index]) min_index = i; // swap minimum element with element at start index temp = arr[start]; arr[start] = arr[min_index]; arr[min_index] = temp; } See selection_sort.c for full program Program is selection_sort.c CS1010 (AY2012/3 Semester 1) ©The McGraw-Hill Companies, Inc. 30

31 8. Selection Sort: Performance
CS1010 Programming Methodology 8. Selection Sort: Performance We choose the number of comparisons as our basis of analysis. Comparisons of array elements occur in the inner loop, where the minimum element is determined. Assuming an array with n elements. Table below shows the number of comparisons for each pass. The total number of comparisons is calculated in the formula below. Such an algorithm is call an n2 algorithm, or quadratic algorithm, in terms of running time complexity. Pass #comparisons 1 n – 1 2 n – 2 3 n – 3 CS1010 (AY2012/3 Semester 1) ©The McGraw-Hill Companies, Inc. 31

32 CS1010 Programming Methodology
8. Selection Sort Selection sort is classified under exchange sort, where elements are exchanged in the process We could search for the minimum element as described earlier, or search for the maximum element and exchange it with the last element of the working array (assuming we sort in ascending order) The latter is described in Lesson 6.6 in the book as an Exchange Maximum Sort CS1010 (AY2012/3 Semester 1) ©The McGraw-Hill Companies, Inc. 32

33 9. Exercise #2: Points and Lines (1/6)
CS1010 Programming Methodology 9. Exercise #2: Points and Lines (1/6) Problem: You are given a list of points on a 2-dimensional plane, each point represented by its integer x- and y-coordinates. You are to sort the points in ascending order of their x-coordinates, and for those with the same x-coordinate, in ascending order of their y-coordinates. Two arrays are used to store the points: array x for their x- coordinates, and array y for their y-coordinates. x[i] and y[i] refer to the point i. You may assume that there are at most 20 points and no two points are the same. Do the sorting by calling Selection Sort only once. How do you adapt the Selection Sort code for this problem? You are given an incomplete program Week10_Points.c This exercise is mounted on CodeCrunch. This is a guided exercise, to show students how we apply the Selection Sort they learned to a new problem that requires them to adapt the Selection Sort, not using it wholesale as presented earlier. In general, such multi-key sorting can be done by performing multi-phase sort. For this problem, sort by y-coordinates first, then sort by x-coordinates. However, this requires the sort to be stable. Selection sort is not stable, hence it cannot be done this way. CS1010 (AY2012/3 Semester 1) ©The McGraw-Hill Companies, Inc. 33

34 9. Exercise #2: Points and Lines (2/6)
CS1010 Programming Methodology 9. Exercise #2: Points and Lines (2/6) In the preceding section, the comparison is done using a simple relational operation: for (i = start_index+1; i < size; i++) if (arr[i] < arr[min_index]) min_index = i; What if the problem deals with more complex data, like this exercise? The simple relational operation above would have to be replaced by a more complex one. Or you could call another function to do it. For example, for this exercise: for (i = start_index+1; i < size; i++) if ( lessThan(x, y, i, min_index) ) min_index = i; CS1010 (AY2012/3 Semester 1) ©The McGraw-Hill Companies, Inc. 34

35 9. Exercise #2: Points and Lines (3/6)
CS1010 Programming Methodology 9. Exercise #2: Points and Lines (3/6) Here’s the incomplete lessThan() function: // Returns 1 if point at index p is "less than" point at index q; // otherwise returns 0. // Point at index p is "less than" point at index q if the former // has a smaller x-coordinate, or if their x-coordinates are the // same, then the former has a smaller y-coordinate. int lessThan(int x[], int y[], int p, int q) { } return (x[p] < x[q]) || ( (x[p] == x[q]) && (y[p] < y[q]) ); CS1010 (AY2012/3 Semester 1) ©The McGraw-Hill Companies, Inc. 35

36 9. Exercise #2: Points and Lines (4/6)
CS1010 Programming Methodology 9. Exercise #2: Points and Lines (4/6) Here’s the incomplete sortPoints() function: // Sort points in ascending order of x-, and then y-coordinates void sortPoints(int x[], int y, int size) { int i, start, min_index, temp; } for (start = 0; start < size-1; start++) { // find the index of minimum element min_index = start; for (i = start+1; i < size; i++) // check if point at index i is "less than" point at min_index if ( lessThan(x, y, i, min_index) ) min_index = i; // swap minimum element with element at start index temp = x[start]; x[start] = x[min_index]; x[min_index]=temp; temp = y[start]; y[start] = y[min_index]; y[min_index]=temp; } CS1010 (AY2012/3 Semester 1) ©The McGraw-Hill Companies, Inc. 36

37 9. Exercise #2: Points and Lines (5/6)
CS1010 Programming Methodology 9. Exercise #2: Points and Lines (5/6) [Do this part after class] After sorting the points, imagine that you trace the points in their order in the sorted array. Write a function traceLines() to compute the sum of the lengths of those lines that are horizontal or vertical. For example, after sorting, here are the points: (1,2), (1,3), (2,1), (2,4), (3,2), (3,3), (3,4), (5,3), (5,6), (6,2), (6,5), (7,2), (10,4), (11,4), (12,2). The vertical and horizontal lines are marked in green. 1 2 3 4 5 6 7 8 9 10 11 12 Sum of lengths of horizontal and vertical lines = = 13 (1,3) (1,2) CS1010 (AY2012/3 Semester 1) ©The McGraw-Hill Companies, Inc. 37

38 9. Exercise #2: Points and Lines (6/6)
CS1010 Programming Methodology 9. Exercise #2: Points and Lines (6/6) Sample run: Enter number of points: 15 Enter x- and y-coordinates of 15 points: 5 3 2 4 : 2 1 After sort: Point # 0: (1,2) Point # 1: (1,3) Point #14: (12,2) Sum of lengths of vertical and horizontal lines = 13 See input file points.in CS1010 (AY2012/3 Semester 1) ©The McGraw-Hill Companies, Inc. 38

39 CS1010 Programming Methodology
10. Bubble Sort Selection sort makes one exchange at the end of each pass. What if we make more than one exchange during each pass? The key idea of the bubble sort is to make pairwise comparisons and exchange the positions of the pair if they are in the wrong order. CS1010 (AY2012/3 Semester 1) ©The McGraw-Hill Companies, Inc. 39

40 10. One Pass of Bubble Sort Done! Q: Is the array sorted?
CS1010 Programming Methodology 10. One Pass of Bubble Sort 1 2 3 4 5 6 7 8 23 17 90 12 44 38 84 77 17 5 23 12 44 90 38 84 77 exchange exchange 17 23 5 90 12 44 38 84 77 17 5 23 12 44 38 90 84 77 exchange exchange 17 5 23 90 12 44 38 84 77 17 5 23 12 44 38 84 90 77 exchange ok exchange What is the meaning behind the name “bubble” sort? Notice the effect of one pass is to migrate the largest element to the last position of the array. In addition, because we are exchanging the pairs if they are out of order, other elements migrate toward the end of the array. If we view the array vertically with the first position at the bottom and the last position at the top, the data movements we see is like bubbles moving toward the surface of water. 17 5 23 12 90 44 38 84 77 17 5 23 12 44 38 84 77 90 exchange Q: Is the array sorted? Q: What have we achieved? Done! CS1010 (AY2012/3 Semester 1) ©The McGraw-Hill Companies, Inc. 40

41 10. Demo #3: Bubble Sort See bubble_sort.c for full program
CS1010 Programming Methodology 10. Demo #3: Bubble Sort // To sort arr in increasing order void bubbleSort(int arr[], int size) { int i, limit, temp; for (limit = size-2; limit >= 0; limit--) { // limit is where the inner loop variable i should end for (i=0; i<=limit; i++) { if (arr[i] > arr[i+1]) { // swap arr[i] with arr[i+1] temp = arr[i]; arr[i] = arr[i+1]; arr[i+1] = temp; } See bubble_sort.c for full program Program is bubble_sort.c CS1010 (AY2012/3 Semester 1) ©The McGraw-Hill Companies, Inc. 41

42 10. Bubble Sort Performance
CS1010 Programming Methodology 10. Bubble Sort Performance Bubble sort, like selection sort, requires n – 1 passes for an array with n elements. The comparisons occur in the inner loop. The number of comparisons in each pass is given in the table below. The total number of comparisons is calculated in the formula below. Like selection sort, bubble sort is also an n2 algorithm, or quadratic algorithm, in terms of running time complexity. Pass #comparisons 1 n – 1 2 n – 2 3 n – 3 CS1010 (AY2012/3 Semester 1) ©The McGraw-Hill Companies, Inc. 42

43 10. Bubble Sort: Enhanced version
CS1010 Programming Methodology 10. Bubble Sort: Enhanced version It is possible to enhance bubble sort algorithm to reduce the number of passes. Suppose that in a certain pass, no swap is needed. This implies that the array is already sorted, and hence the algorithm may terminate without going on to the next pass. You will write this enhanced version for your discussion session this week. CS1010 (AY2012/3 Semester 1) ©The McGraw-Hill Companies, Inc. 43

44 11. More Sorting Algorithms
CS1010 Programming Methodology 11. More Sorting Algorithms We have introduced 2 basic sort algorithms. Together with the Insertion Sort algorithm, these 3 are the simplest sorting algorithms. However, they are very slow, as their running time complexity is quadratic. Faster sorting algorithms exist and are covered in more advanced modules such as CS1020. Students will work on Insertion Sort in the discussion session. CS1010 (AY2012/3 Semester 1) ©The McGraw-Hill Companies, Inc. 44

45 12. Animated Sorting Algorithms
CS1010 Programming Methodology 12. Animated Sorting Algorithms There are a number of animated sorting algorithms on the Internet Here are two sites: There are also folk dances based on sorting! Selection sort with Gypsy folk dance Bubble-sort with Hungarian folk dance You can show them the animated algorithms. Students normally like to see such things. There are even youtube video clips on folk dances based on sorting! CS1010 (AY2012/3 Semester 1) ©The McGraw-Hill Companies, Inc. 45

46 13. Exercise #3: Module Sorting (take-home) (1/2)
CS1010 Programming Methodology 13. Exercise #3: Module Sorting (take-home) (1/2) Week10_SortModules.c: Given two arrays: one containing the module codes, and the other containing the number of students enrolled in the modules. Sort the modules in ascending order of student enrolment, using Selection Sort, Bubble Sort, or Insertion Sort (if you happen to know it). You may assume that there are at most 10 modules and a module code is at most 7 characters long. This is a take-home exercise. This exercise is mounted on CodeCrunch. Program is Week10_SortModules.c CS1010 (AY2012/3 Semester 1)

47 13. Exercise #3: Module Sorting (take-home) (2/2)
CS1010 Programming Methodology 13. Exercise #3: Module Sorting (take-home) (2/2) Sample run: Enter number of modules: 10 Enter module codes and student enrolment: CS CS CS1010E 358 CS IS IS IS GEK IT MA1101S 123 Input Sorted by student enrolment: IT GEK IS IS MA1101S 123 CS IS CS CS CS1010E 358 Output See input file modules.in CS1010 (AY2012/3 Semester 1)

48 Summary for Today Searching algorithms Basic sorting algorithms
CS1010 Programming Methodology Summary for Today Searching algorithms Linear (sequential) search Binary search Basic sorting algorithms Selection sort Bubble sort CS1010 (AY2012/3 Semester 1)

49 Announcements/Things-to-do
CS1010 Programming Methodology Announcements/Things-to-do Revise Chapter 6: Numeric Arrays Lesson 6.6 Bubble Sort, Exchange Maximum Sort Exercise #3 Module Sorting PE2 this Saturday 27 October 2012, Saturday See module website for details This Friday is Hari Raya Haji No Discussion Session Next week’s lecture: Recursion: Lesson 8.6 CS1010 (AY2012/3 Semester 1)

50 CS1010 Programming Methodology
End of File


Download ppt "CS1010: Programming Methodology"

Similar presentations


Ads by Google