QUICK SORT ALGORITHM We define the midpoint of

  • Slides: 5
Download presentation
QUICK SORT ALGORITHM We define the mid-point of a list as having position [½(N+1)]

QUICK SORT ALGORITHM We define the mid-point of a list as having position [½(N+1)] where [x] is the smallest integer greater than or equal to x and N is the number of elements in the list e. g. 3, 6, 7, 11, 15 N=5 [½ (5+1)] = [3] = 3 mid-point = 7 e. g. A, C, Y, B, D, R N=6 [½ (6+1)] = [3½] = 4 mid-point = B

Step 1 Locate the pivot element (use the element at the mid-point) Step 2

Step 1 Locate the pivot element (use the element at the mid-point) Step 2 Split the list into two sub-lists. Sub-list L 1 contains those numbers less than or equal to the pivot and are written to the left of the pivot. Sub-list L 2 contains those numbers greater than the pivot element and are written to the right of the pivot. Do not reorder the numbers in the sub-lists Step 3 Repeat Step 2 on each sub-list and each successive sub-list Step 4 Stop when each sub-list contains only one number. The list is now sorted!

Use a quick-sort to arrange these numbers in numerical order: L 1 L 3

Use a quick-sort to arrange these numbers in numerical order: L 1 L 3 27 15 2 19 16 1 15 2 16 1 19 27 L 2 15 Remember 2 16 the numbers 19 27 not 1 to reorder in the sub-list 1 2 15 16 19 27 L 4 L 2 contains only one L 5 number and is sorted Mid-point of = [½(6+1)] L 3 [½(3+1)] = [3½] [2] 4 th = =2 nd number = 19= STOP Mid-point of L 1 =15 [½(4+1)] [2½] 3 rdnumber =2 16 1 2 16= = 19 27 Numbers in less in L 1 L 3 than less 19 than are: 16 2 are: Remaining sub-lists only have before one member, so the list This sub-list L 1 is L 3 L 4 is written before the pivot is sorted! Number(s)more Numbers morethan 2 19 are: This sub-list L 5 L 2 is written after the pivot

Use a quick-sort to arrange these letters in alphabetical order: Y T A B

Use a quick-sort to arrange these letters in alphabetical order: Y T A B F S F L A B F F Y T S L A B F F L S Y T A B F F L S T Y STOP

Use a quick-sort to arrange these numbers in numerical order: 16 21 15 3

Use a quick-sort to arrange these numbers in numerical order: 16 21 15 3 12 9 18 17 27 18 17 21 before 15 12 27 Nothing 18 17 27 Nothing 16 before 21 1518 17 27 15 27 6 You try it! 3 6 9 16 21 3 6 9 12 16 3 6 9 12 15 16 17 18 21 27 21 12 15 STOP