Sorting - PowerPoint PPT Presentation

1 / 10
About This Presentation
Title:

Sorting

Description:

Barney. Pebbles. Fred. Wilma. Dino. Barney. Pebbles. Fred. Dino ... Barney. Dino. Fred. Pebbles. Wilma. Write the code. Loop over the size of the list minus 1 ... – PowerPoint PPT presentation

Number of Views:67
Avg rating:3.0/5.0
Slides: 11
Provided by: mil94
Category:
Tags: barney | sorting

less

Transcript and Presenter's Notes

Title: Sorting


1
Sorting
  • CS0004
  • Chapter 7.4

2
Why?
  • Often times we just need to sort
  • Improve search
  • Recall binary search
  • Allow us to prioritize a large list
  • What to do next
  • Make things pretty
  • For the user )

3
Sorting
  • Sorting is an algorithm for ordering an array
  • Descending
  • Ascending
  • Many, Many, Many different ways but..
  • Bubble Sort
  • Shell Sort

4
Swap
  • Both bubble and shell use a function called swap
  • temp varl
  • varl var2
  • var2 temp
  • The above psuedo-code makes var1 equal to var2
    and var2 equal to var1

5
Using Swap
  • Private Sub btnAlphabetize_Click(...) _
  • Handles btnAlphabetize.Click
  • Dim firstWord, secondWord, temp As String
  • firstWord txtFirstWord.Text
  • secondWord txtSecondWord.Text
  • If (firstWord secondWord) Then
  • temp firstWord
  • firstWord secondWord
  • secondWord temp
  • End If
  • txtResult.Text firstWord " before " _
  • secondWord
  • End Sub

6
Bubble Sort - Idea
  • Compare the first and second items, if out of
    order then swap them
  • Compare the second and third items, if out of
    order then swap them
  • Repeat for all other items
  • 1/2, 2/3, 3/4, 4/5, 5/6 n-1/n
  • Now, the last item is in the proper place, called
    first pass
  • Repeat steps 1-3 again ignoring the last element
  • Repeat n-1 steps until all are in proper place

7
Example
Pebbles Barney Wilma Fred Dino
First Pass
Barney Pebbles Fred Dino Wilma
Second Pass
8
Example
Barney Fred Dino Pebbles Wilma
Third Pass
Barney Dino Fred Pebbles Wilma
Fourth Pass
9
Write the code
  • Loop over the size of the list minus 1
  • Then loop from the start of the list to the end
    minus the number of times we have already looped
  • If item is out of order with previous
  • swap them
  • End If
  • End Loop
  • End Loop

10
Shell Sort
  • Much more complex
  • General idea
  • Compare items at further distance (known as the
    gap) and swap like bubble sort
  • Then reduce the gap size by 1 and do it again
  • Continue until the gap size is set to 0, meaning
    we are comparing neighbors (as we do in bubble
    sort)
  • Not required to understand, details in book
Write a Comment
User Comments (0)
About PowerShow.com