This preview shows pages 1–8. Sign up to view the full content.
This preview has intentionally blurred sections. Sign up to view the full version.
View Full DocumentThis preview has intentionally blurred sections. Sign up to view the full version.
View Full DocumentThis preview has intentionally blurred sections. Sign up to view the full version.
View Full DocumentThis preview has intentionally blurred sections. Sign up to view the full version.
View Full Document
Unformatted text preview: 20012002 Fall Week 11+Michael Fung, CS&E, The Chinese University of HK1CSC1500 Computer Principles and ProgrammingHow to Program a Computer in C and General Introduction to ComputingLecture 11 Supplement20012002 Fall Week 11+Michael Fung, CS&E, The Chinese University of HK2SortingTo put a set of data in order.Given 9, 8, 3, 5, 7Ascending order: 8, 3, 5, 7, 9Descending order: 9, 7, 5, 3, 8There are many strategies (algorithms) for sorting.One of the simplest ones is Selection Sort.20012002 Fall Week 11+Michael Fung, CS&E, The Chinese University of HK3Swap Two NumbersGiven integers i and j.Swap (exchange) their contents.int i = 8, j = 3;i = j;/* i becomes 3 */j = i;/* j becomes i, thus 3 also *//* really okay? */ORint i = 8, j = 3;i = j = i;/* j becomes 8, then *//* i becomes j, thus 8 also *//* another nightmare: i = (j = i) */20012002 Fall Week 11+Michael Fung, CS&E, The Chinese University of HK4Get the Temp. Job Doneint i = 8, j = 3;int temp;temp = j;/* keep a copy of value of j */j = i;/* overwrite j by value of i */i = temp;/* restore value of j to i */Given us 2 lockers, swap their contents!Get the Giraffe out and put it aside.Move the Elephant to the emptiedlocker.Store the Giraffe into the other emptiedone.*** Not really empty, we make copies ***20012002 Fall Week 11+Michael Fung, CS&E, The Chinese University of HK5Sort 2 NumbersGiven 2 integers stored in i and j.int i = 8, j = 3;if (j < i) {/* if j is smaller */int temp = i; /* exchange contents of i and j */i = j;/* making the smaller value in i */j = temp;}printf(Ordered: %d,%d\n, i, j);How about sorting three, four, or any?An array is needed.To swap the order on the fly.20012002 Fall Week 11+Michael Fung, CS&E, The Chinese University of HK6Finding the Min of N Numbersint N = {5, 1, 3};int i, min;min = N[0];for (i = 1; i < 3; i++)/* note: start with i = 1 */if (N[i] < min)min = N[i];At the beginning, let the first element be the King.Then, compare the elements onebyone with the King.Selectanother King when appropriate.20012002 Fall Week 11+Michael Fung, CS&E, The Chinese University of HK7Finding Kings OneByOneThats the idea of the Selection Sort!...
View Full
Document
 Spring '10
 fung
 Sort

Click to edit the document details