180 likes | 341 Views
Computer Science 101 A Survey of Computer Science. Sorting. Sorting. Some of the most heavily used algorithms are those for sorting data. Arranging data into numerical or alphabetical order for purposes of Reports by category Summarizing data Searching data. Sorting (cont).
E N D
Sorting • Some of the most heavily used algorithms are those for sorting data. • Arranging data into numerical or alphabetical order for purposes of • Reports by category • Summarizing data • Searching data
Sorting (cont) • Given: n, N1,N2,…,Nn • Want: Rearrangement M1,M2,…,Mn where M1… Mn 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
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. • Variables: • U - Marker for unsorted section • L - Position of largest so far • C - Current position
Selection Sort - The algorithm Set U to nWhile U>1 Set L to 1 Set C to 2 While C ≤ U do If N(C) > N(L) then Set L to C Set C to C+1 end-of-loop Exchange N(L) and N(U) Set U to U-1end-of-loopStop
L U L U 5 19 12 5 19 12 6 6 9 9 6 9 9 6 9 9 9 6 6 9 6 L U C C 5 19 C U L 5 19 12 L U C U 19 5 12 L 5 12 19 C C L U 12 5 19 12 C Selection Sort - Example (Pass 1) 12
L U L U 5 12 12 5 19 6 9 9 6 9 6 6 9 6 9 6 19 C C L U L U 5 12 19 5 19 12 C C L U 9 5 12 19 C L U 12 19 5 C Selection Sort - Example (Pass 2)
L U 12 6 6 6 6 6 C L U 5 12 19 5 9 19 C 9 LU 19 5 9 12 19 C L L U U 5 5 9 9 12 12 19 19 C C Selection Sort - Example (Pass 3)
L U U 5 9 12 19 6 9 12 19 5 6 5 6 C L U 5 12 C LU 9 12 19 6 C 9 19 Selection Sort - Example (Pass 4)
Sorting - Bubble Sort • Strategy: • Pass through the list from left to right. • Compare each element with the one to its left. • Swap them if they are out of order. • Such a pass will put largest at the right end. • Continue making these passes until sorted. • Variables: • U - Marker for unsorted section • C - Current position
Bubble Sort - The algorithm Set U to nWhile U > 1 do Set C to 2 While C ≤ U do If N(C) < N(C-1) then Exchange N(C) and N(C-1) Set C to C+1 end-of-loop Set U to U-1end-of-loopStop
U U 5 19 3 9 6 3 6 5 5 5 9 5 6 6 19 3 C C U U 9 19 3 9 19 C C 6 U 19 3 9 C Bubble Sort - Example (Pass 1)
U 9 6 3 9 5 3 5 5 3 5 19 C U C 9 6 19 C 6 6 3 9 U U 19 19 C Bubble Sort - Example (Pass 2)
U U U 9 9 5 5 5 9 C C 6 6 3 6 3 3 19 19 19 C Bubble Sort - Example (Pass 3)
3 9 9 9 3 5 U U U C 3 5 5 6 6 6 C 19 19 19 Bubble Sort - Example (Pass 4)
You take the big uns and I'll get the little doggies!