Sorting - sjiang1.github.io · Sorting •Selection sort •Insertion sort •Bubble sort •Heap...

Post on 27-May-2019

280 views 4 download

Transcript of Sorting - sjiang1.github.io · Sorting •Selection sort •Insertion sort •Bubble sort •Heap...

11/19/2018

Data Structure & Algorithm

1

• Sorting

Sorting

• Selection sort

• Insertion sort

• Bubble sort

• Heap sort

• Merge sort

• Quick sort

• Bucket sort

2

Selection Sort

3

(textbook)

Selection Sort

4

https://www.khanacademy.org/computing/computer-science/algorithms/sorting-algorithms/a/selection-sort-pseudocode

practice: write the pseudocode for selection sort

Selection Sort

5

i = 0while i < length(A) - 1

min_index = ij = i + 1while j < length(A)

if A[min_index] > A[j]min_index = j

end ifj ++

end while

int tmp = A[min_index]A[min_index] = A[i]A[i] = tmpi ++

end while

Selection Sort

6

Insertion Sort

7

https://www.geeksforgeeks.org/insertion-sort/

Insertion Sorting

8

https://en.wikipedia.org/wiki/Insertion_sort

Bubble Sort

bubbleSort(A):

while true do

swapped = false

for i = 1 to n-1 inclusive do

if A[i-1] > A[i] then

swap( A[i-1], A[i] )

swapped = true

end if

end for

n = n - 1

until not swapped

9

https://en.wikipedia.org/wiki/Bubble_sort

Bubble Sort

10

Heap Sort

1. Build a max heap from an array

2. Remove the first element of the heap and put it to the end of the array.

3. Do the second step until the heap is empty

11

• leftchild(i) = 2i + 1

• rightchild(i) = 2i + 2

• parent(i) = floor((i-1)/2)

Heap Sort - Heapify

heapify(a, start, end):

root = start

while leftchild(root) <= end do

child = leftchild(root)

if rightchild(root) <= end do

rchild = rightchild(root)

if a[rchild] > a[child] do child = rchild done

done

if a[child] <= a[root] do return

else do

swap(a[root], a[child])

root = child

done

12

// a is the array, // start is the root, end is the last index of the heap

Heap Sort - buildheap

buildheap(a, count): // a is the array, count is the length

start = parent(count-1)

while start >= 0 do

heapify(a, start, count – 1)

start --

13

Heap Sort

14

Merge Sort

Divide-and-Conquer

• 1. Divide: if the input size is smaller than a certain threshold, solve the problem directly using a straightforward method and return the solution so obtained. Otherwise, divide the input data into two or more disjoint subsets

• 2. Conquer: Recursively solve the subproblems associated with the subsets

• 3. Combine: Take the solutions to the subproblems

15

Merge Sort

16

Merge Sort

17

Merge Sort

18

Quick Sort

19

Quick Sort

Textbook: Sec. 12.2, P. 549

20

Bubble Sort

21

Assignment 11

GitHub: https://classroom.github.com/a/cQWGbG5-

22