Presentation is loading. Please wait.

Presentation is loading. Please wait.

Computer Science 111 Fundamentals of Computer Programming I

Similar presentations


Presentation on theme: "Computer Science 111 Fundamentals of Computer Programming I"— Presentation transcript:

1 Computer Science 111 Fundamentals of Computer Programming I
Sorting

2 Sequential Search Algorithm
Given: List of values v0,v1,…,vn Target value, T Output: Location of T if in list and some signal if T is not in list Strategy: Use variables: i for current location in list Found to indicate whether T located or not Initialize i=0, Found=false Pass through the list sequentially

3 Pseudocode for Sequential Search
Set Found to false Set Loc to -1 Set i to 0 While not Found and i<n if vi = T Set Loc to i Set Found to true else Set i to i+1

4 An implementation of Sequential Search

5 Can we find the largest?

6 Algorithm to Find Largest
Given: List of numbers A0,A1,…,An-1 Output: Largest value in list and its position Strategy: Use variables: i for current location in list Largest for largest value found so far LargeLoc for position of largest found so far Initialize Largest=A0,LargeLoc=0,i=1 Pass through the list sequentially

7 Algorithm to Find Largest (cont)
Set Largest to A0 Set LargeLoc to 0 Set i to 1 While i < n do if Ai > Largest then Set Largest to Ai Set LargeLoc to i Set i to i+1 Output Largest, LargeLoc

8 An implementation of findLargest

9 Sorting One of the most common activities of a computer is sorting data. Arranging data into numerical or alphabetical order for purposes of Reports by category Summarizing data Searching data

10 Sorting (cont) Given: n, N0,N1,…,Nn-1
Want: Rearrangement M0,M1,…,Mn-1 where M0…  Mn-1 according to the appropriate understanding of . There are many well-known algorithms for doing this. Preference may be due to List size Degree of order already present Ease of programming Program available

11 Sorting - Selection Sort
Strategy: Find the largest element in list. Swap it with last element in list. Find next largest. Swap it with next to last element in list Etc.

12 Unsorted List

13 Selection Sort

14 Selection Sort - The algorithm
Set U to n-1 While U>0 LargeLoc = Largest(0,U) Swap values at locations U and LargeLoc Set U to U-1

15 Implementation of Selection Sort

16 Sorry, but I must take exception to that ...


Download ppt "Computer Science 111 Fundamentals of Computer Programming I"

Similar presentations


Ads by Google