Chapter 2.9 Sorting Arrays. Sort Algorithms A set of records is given Each record is identified by a certain key One wants to sort the records according.

Slides:



Advertisements
Similar presentations
Consider an array of n values to be sorted into ascending order. Sorting.
Advertisements

Chapter 3 Brute Force Brute force is a straightforward approach to solving a problem, usually directly based on the problem’s statement and definitions.
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Eighth Edition by Tony Gaddis,
Sorting Part 4 CS221 – 3/25/09. Sort Matrix NameWorst Time Complexity Average Time Complexity Best Time Complexity Worst Space (Auxiliary) Selection SortO(n^2)
Sorting Chapter 8 CSCI 3333 Data Structures.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Programming Logic & Design Second Edition by Tony Gaddis.
Sorting I Chapter 8 Kruse and Ryba. Introduction Common problem: sort a list of values, starting from lowest to highest. –List of exam scores –Words of.
Sorting. Sorting Considerations We consider sorting a list of records, either into ascending or descending order, based upon the value of some field of.
Chapter 9: Searching, Sorting, and Algorithm Analysis
Lesson Plan - 2: Bubble Sort, Quick Sort
Chapter 3: Divide and Conquer
Sorting Algorithms n 2 Sorts ◦Selection Sort ◦Insertion Sort ◦Bubble Sort Better Sorts ◦Merge Sort ◦Quick Sort ◦Radix Sort.
Chapter 19: Searching and Sorting Algorithms
1 Sorting Problem: Given a sequence of elements, find a permutation such that the resulting sequence is sorted in some order. We have already seen: –Insertion.
Data Structures and Algorithms
Sorting Chapter 9.
Computation for Physics 計算物理概論 Algorithm. An algorithm is a step-by-step procedure for calculations. Algorithms are used for calculation, data processing,
Ver. 1.0 Session 5 Data Structures and Algorithms Objectives In this session, you will learn to: Sort data by using quick sort Sort data by using merge.
CHAPTER 11 Sorting.
Searches & Sorts V Deena Engel’s class Adapted from W. Savitch’s text An Introduction to Computers & Programming.
Sorting Chapter 10.
Objectives Learn how to implement the sequential search algorithm Explore how to sort an array using the selection sort algorithm Learn how to implement.
S: Application of quicksort on an array of ints: partitioning.
Sorting Chapter 10. Chapter 10: Sorting2 Chapter Objectives To learn how to use the standard sorting methods in the Java API To learn how to implement.
© 2006 Pearson Addison-Wesley. All rights reserved10 A-1 Chapter 10 Algorithm Efficiency and Sorting.
Sorting Chapter 12 Objectives Upon completion you will be able to:
Week 11 Sorting Algorithms. Sorting Sorting Algorithms A sorting algorithm is an algorithm that puts elements of a list in a certain order. We need sorting.
Page 1 Data Structures in C for Non-Computer Science Majors Kirs and Pflughoeft Searching and Sorting Chapter 9.
Chapter 16: Searching, Sorting, and the vector Type.
Fall 2013 Instructor: Reza Entezari-Maleki Sharif University of Technology 1 Fundamentals of Programming Session 17 These.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 19: Searching and Sorting Algorithms.
Chapter 19: Searching and Sorting Algorithms
HKOI 2006 Intermediate Training Searching and Sorting 1/4/2006.
Computer Science Searching & Sorting.
Merge Sort. What Is Sorting? To arrange a collection of items in some specified order. Numerical order Lexicographical order Input: sequence of numbers.
Chapter 10 B Algorithm Efficiency and Sorting. © 2004 Pearson Addison-Wesley. All rights reserved 9 A-2 Sorting Algorithms and Their Efficiency Sorting.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 19: Searching and Sorting.
Chapter 2.8 Search Algorithms. Array Search –An array contains a certain number of records –Each record is identified by a certain key –One searches the.
© 2006 Pearson Addison-Wesley. All rights reserved10 A-1 Chapter 10 Algorithm Efficiency and Sorting.
© 2006 Pearson Addison-Wesley. All rights reserved10 B-1 Chapter 10 (continued) Algorithm Efficiency and Sorting.
Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Modified for use by MSU Dept. of Computer Science.
Chapter 18: Searching and Sorting Algorithms. Objectives In this chapter, you will: Learn the various search algorithms Implement sequential and binary.
1 Introduction to Sorting Algorithms Sort: arrange values into an order Alphabetical Ascending numeric Descending numeric Two algorithms considered here.
3 – SIMPLE SORTING ALGORITHMS
1 Sorting (Bubble Sort, Insertion Sort, Selection Sort)
Chapter 8 Sorting and Searching Goals: 1.Java implementation of sorting algorithms 2.Selection and Insertion Sorts 3.Recursive Sorts: Mergesort and Quicksort.
Review 1 Selection Sort Selection Sort Algorithm Time Complexity Best case Average case Worst case Examples.
Sorting Algorithms: Selection, Insertion and Bubble.
Sorting and Searching by Dr P.Padmanabham Professor (CSE)&Director
1 Searching and Sorting Searching algorithms with simple arrays Sorting algorithms with simple arrays –Selection Sort –Insertion Sort –Bubble Sort –Quick.
5.3 Sorting Techniques. Sorting Techniques Sorting is the process of putting the data in alphabetical or numerical order using a key field primary key.
Sorting 1. Insertion Sort
Chapter 9 Sorting 1. The efficiency of data handling can often be increased if the data are sorted according to some criteria of order. The first step.
Chapter 9 Sorting. The efficiency of data handling can often be increased if the data are sorted according to some criteria of order. The first step is.
Elementary Sorting 30 January Simple Sort // List is an array of size == n for (i = 1; i < n; i++) for (j = i+1; j List[j])
Course Code #IDCGRF001-A 5.1: Searching and sorting concepts Programming Techniques.
Review 1 Insertion Sort Insertion Sort Algorithm Time Complexity Best case Average case Worst case Examples.
CSE 326: Data Structures Lecture 23 Spring Quarter 2001 Sorting, Part 1 David Kaplan
Review 1 Merge Sort Merge Sort Algorithm Time Complexity Best case Average case Worst case Examples.
Chapter 9: Sorting1 Sorting & Searching Ch. # 9. Chapter 9: Sorting2 Chapter Outline  What is sorting and complexity of sorting  Different types of.
Experimental Study on the Five Sort Algorithms You Yang, Ping Yu, Yan Gan School of Computer and Information Science Chongqing Normal University Chongqing,
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy.
Chapter 16: Searching, Sorting, and the vector Type.
Sort Algorithm.
CSc 110, Spring 2017 Lecture 39: searching.
Chapter 4.
Searching.
Applications of Arrays
Presentation transcript:

Chapter 2.9 Sorting Arrays

Sort Algorithms A set of records is given Each record is identified by a certain key One wants to sort the records according to an order relation defined for the key.

Sort Algorithms Key Preparation Array sorting –Straight Selection Sort –Straight Insertion Sort –Bubble Sort –Quicksort

Sort Algorithms Key Preparation Array sorting –Straight Selection Sort –Straight Insertion Sort –Bubble Sort –Quicksort

Key Preparation Alphabetical sorting of names is quite common Names can contain upper- and lower case letters Names can also contain spaces and special signs The sorting algorithm should not take into account –The case of the letters –The special signs and spaces The names will be transformed into keys by a special procedure taking into account the above specifications.

Alphabetical Key PROCEDURE MakeKey(VAR Names, Key: ARRAY OF CHAR); VARn,k: CARDINAL; Offset: INTEGER; BEGIN Offset := ORD(“a”)-ORD(“A”); Lname := HIGH(Name); Lkey := HIGH(Key); n := 0; k := 0; REPEAT c := Name[n]; IF (c>=“A”)AND(c<=“Z”) (* Uppercase Letter *) THEN Key[k] := c; n:=n+1; k:=k+1; ELSIF (c>=“a”) AND (c<=“z”) (* Lowercase Letter *) THEN Key[k] := CHR(ORD(c)-Offset); n:=n+1; k:=k+1; ELSE n:=n+1 (* Not a Letter, ignore *) END; (* IF *) UNTIL (n> Lname) OR (k> Lkey); FOR k := k TO Lkey DO Key[k] := “ “ END; END MakeKey;

Sort Algorithms Key Preparation Array sorting –Straight Selection Sort –Straight Insertion Sort –Bubble Sort –Quicksort

Array Sort PROCEDURE Sort –One VAR parameter: The Array to be sorted Contains n Items Index in the range 0..n Item with index 0 is not used –After execution of Sort, The Array is sorted according to the order relation defined for the Key field

Sort Algorithms Key Preparation Array sorting –Straight Selection Sort –Straight Insertion Sort –Bubble Sort –Quicksort

Selection Sort ?? ?? ?? ?? ??

Selection Sort FOR i := 1 TO Size-1 DO Find m such that A[m].Key = min (A[i].Key..A[Size].Key) Swap A[i] and A[m] m := i ; MinKey := A[m].Key; FOR j := i+1 TO Size DO m := j; MinKey := A[m].Key A[j].Key < MinKey Yes

Selection Sort PROCEDURE Sort(VAR A ARRAY OF Item); VAR i,j,m,Size : CARDINAL; MinKey : KeyType; PROCEDURE Swap(VAR X,Y : Item); (* Exchange values of X and Y *) END Swap; BEGIN Size := High(A); FOR i := 1 TO Size DO (* Find m, the index of the smallest key between items [i+1] and [Size] *) Swap(A[i],A[m]) END; (* FOR *) END Sort;

Selection Sort Find the smallest key in the remaining Array m := i; MinKey := A[m].Key; FOR j := i + 1 TO Size DO IF A[j].Key < MinKey THEN m := j; MinKey := A[m].Key END (* IF *) END; (* FOR *)

Procedure Swap PROCEDURE Swap(VAR X,Y : Item); VAR Z : Item; BEGIN Z := X; X := Y; Y := Z END Swap;

Selection Sort Performance n   i  ()1 i n   1 1 i n  i  2 nn  Number of Comparisons = = = Number of swaps <= n

Sort Algorithms Key Preparation Array sorting –Straight Selection Sort –Straight Insertion Sort –Bubble Sort –Quicksort

Insertion Sort ??

Insertion Sort FOR i := 2 TO Size DO X := A[i] Insert X at the appropriate location between A[1] and A[i], using A[0] as a sentinel A[0] := X; j := i; WHILE X.Key < A[j-1].Key DO A[j] := A[j-1]; DEC( j ); A[j] := X

Insertion Sort PROCEDURE Sort(VAR A ARRAY OF Item); VAR i,j,m,Size : CARDINAL; X : Item; BEGIN Size := High(A); FOR i := 2 TO Size DO X := A[i]; A[0] := X; j := i; WHILE X.Key <= A[j-1].Key DO A[j] := A[j-1]; DEC(j) END; A[j] := X END; (* FOR *) END Sort;

Insertion Sort Performance * Comparisons –minimum : n - 1 –average : ( n 2 + n - 2 ) / 4 –maximum : ( n 2 - n ) / Moves –minimum : 2 ( n - 1 ) –average : ( n n - 10 ) / 4 –maximum : ( n n - 4 ) / 2 * See N. Wirth, Algorithms + data structures = programs, p85

Sort Algorithms Key Preparation Array sorting –Straight Selection Sort –Straight Insertion Sort –Bubble Sort –Quicksort

Bubble Sort (1) ?? ?? ?? ?? ?? ?? ?? ?? ??

Bubble Sort (2) ?? ?? ?? ?? ?? ?? ??

Bubble Sort FOR i := 1 TO Size-1 DO Move the largest element among the elements [1] to [Size-I] to the position [Size – i + 1] FOR j := 1 TO Size - I DO A[j].Key > A[j+1].Key Swap(A[j],A[j+1])

Bubble Sort PROCEDURE Sort(VAR A ARRAY OF Item); VAR i,j,Size : CARDINAL; BEGIN Size := High(A); FOR i := 1 TO Size-1 DO FOR j := 1 TO Size-i DO IF A[j].Key >A[j+1].Key THEN Swap(A[j],A[j+1]) END (* IF *) END (* FOR j *) END; (* FOR i *) END Sort;

Bubble Sort Performance  i i n   1 1 nn  2 2 Number of Comparisons = = Number of swaps <= nn  2 2 Rem : It is relatively easy to improve the average performance by detecting when the array is entirely sorted but worst case performance remains poor.

Bubble Sort PROCEDURE Sort(VAR A ARRAY OF Item); VAR i,j,Size : CARDINAL; InOrder: BOOLEAN; BEGIN Size := High(A); i := 0; REPEAT Inorder := TRUE; i := i + 1; FOR j := 1 TO Size - i DO IF A[j].Key >A[j+1].Key THEN Swap(A[j],A[j+1]); InOrder := FALSE; END (* IF *) END (* FOR j *) UNTIL InOrder OR (i = Size-1); END Sort;

Sort Algorithms Key Preparation Array sorting –Straight Selection Sort –Straight Insertion Sort –Bubble Sort –Quicksort

Quicksort Partition array A into two parts A1 and A2 in such a way that all keys in A1 are Pivot (Pivot has a value close to the median of key values) More than 1 element in A1 ? Apply QuickSort to array A1 More than 1 element in A2 ? Apply QuickSort to array A2 Yes

Quicksort Performance To sort an array with n elements n n/2 n/4 n/ Number of partition levels =

Quicksort Performance Number of comparisons per level –To partition an array with n elements : n –To partition m arrays with each n/m elements : n Number of partition levels –Average length at level k : n / 2 k –Levels needed to reach length = 1 : log 2 n – Total number of comparisons to sort n elements : C = n log 2 n

Quicksort Performance Example Array with 10 6 elements Processor performing 10 6 comparisons per second Quicksort C = n log 2 n = 10 6 log = time = = 20 s. Selection sort C = ( n 2 + n - 1 ) / 2 = ( ) / 2 ~ time = = s ~ 5 days !!!

Quick Sort ?? ?? ?? ?? ?? ??

Quicksort Algorithm (1) Pivot := A[(first+last)DIV2].Key Partition array A into two parts A1 and A2 in such a way that all keys in A1 are Pivot More than 1 element in A1 ? Apply QuickSort to array A1 More than 1 element in A2 ? Apply QuickSort to array A2 Yes

Quicksort Algorithm (2) i := first; j := last; UNTIL i > j WHILE A[i].Key < Pivot INC(i) WHILE A[j].Key > Pivot DEC(j) Swap (A[i],A[j]); INC(i); DEC(j); i < j Yes ij

Quicksort Algorithm (3) i := first; j := last; UNTIL i > j WHILE A[i].Key < Pivot INC(i) WHILE A[j].Key > Pivot DEC(j) Swap (A[i],A[j]); INC(i); DEC(j); i < j Yes ij

Quicksort Algorithm (4) i := first; j := last; UNTIL i > j WHILE A[i].Key < Pivot INC(i) WHILE A[j].Key > Pivot DEC(j) Swap (A[i],A[j]); INC(i); DEC(j); i < j Yes ij

Quicksort Algorithm (5) i := first; j := last; UNTIL i > j WHILE A[i].Key < Pivot INC(i) WHILE A[j].Key > Pivot DEC(j) Swap (A[i],A[j]); INC(i); DEC(j); i < j Yes ij

Optimized Quicksort Partition array A into two parts A1 and A2 in such a way that all keys in A1 are Pivot (Pivot has a value close to the median of key values) More than Min elements in A1 ? Apply QuickSort to array A1 More than Min elements in A2 ? Apply QuickSort to array A2 Yes Apply Insertion Sort to entire array A