0% found this document useful (0 votes)
29 views

Sorting

The document discusses various sorting algorithms including selection sort, bubble sort, insertion sort, shell sort, merge sort, heap sort, and quicksort. It provides descriptions of each algorithm, examples of how they work, and analysis of their time and space complexities. The most efficient algorithms are merge sort and heapsort which have guaranteed performance of O(n log n), while quicksort also has average case performance of O(n log n) but worst case of O(n2) if pivots are chosen poorly. Selection sort, bubble sort, and insertion sort have quadratic time complexities of O(n2).

Uploaded by

TANISHQ KALE
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views

Sorting

The document discusses various sorting algorithms including selection sort, bubble sort, insertion sort, shell sort, merge sort, heap sort, and quicksort. It provides descriptions of each algorithm, examples of how they work, and analysis of their time and space complexities. The most efficient algorithms are merge sort and heapsort which have guaranteed performance of O(n log n), while quicksort also has average case performance of O(n log n) but worst case of O(n2) if pivots are chosen poorly. Selection sort, bubble sort, and insertion sort have quadratic time complexities of O(n2).

Uploaded by

TANISHQ KALE
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

Sorting

1
• How to use standard sorting methods
• How to implement these sorting algorithms:

• Selection sort
• Bubble sort
• Insertion sort
• Shell sort
• Merge sort
• Heap sort
• Quick sort
• Understand the performance of these algorithms

• Which to use for small arrays


• Which to use for medium arrays
• Which to use for large arrays
Selection Sort
• A relatively easy to understand algorithm
• Sorts an array in passes
• Each pass selects the next smallest element
• At the end of the pass, places it where it
belongs

• Efficiency is O(n2), hence called a quadratic sort


• Performs:
• O(n2) comparisons
• O(n) exchanges (swaps)
Selection Sort Algorithm

1. for fill = 0 to n-2 do // steps 2-6 form a pass


2. set posMin to fill
3. for next = fill+1 to n-1 do
4. if item at next < item at posMin
5. set posMin to next
6. Exchange item at posMin with one at fill
Selection Sort Example
35 65 30 60 20 scan 0-4, smallest 20
swap 35 and 20
20 65 30 60 35 scan 1-4, smallest 30
swap 65 and 30
20 30 65 60 35 scan 2-4, smallest 35
swap 65 and 35
20 30 35 60 65 scan 3-4, smallest 60
swap 60 and 60
20 30 35 60 65 done
Bubble Sort

• Compares adjacent array elements


• Exchanges their values if they are out of order

• Smaller values bubble up to the top of the array


• Larger values sink to the bottom
Bubble Sort Example
Bubble Sort Algorithm

1. do
2. for each pair of adjacent array elements
3. if values are out of order
4. Exchange the values
5. while the array is not sorted
Bubble Sort Algorithm, Refined

1. do
2. Initialize exchanges to false
3. for each pair of adjacent array elements
4. if values are out of order
5. Exchange the values
6. Set exchanges to true
7. while exchanges
Analysis of Bubble Sort

• Excellent performance in some cases


• But very poor performance in others!
• Works best when array is nearly sorted to begin with
• Worst case number of comparisons: O(n2)
• Worst case number of exchanges: O(n2)
• Best case occurs when the array is already sorted:
• O(n) comparisons
• O(1) exchanges (none actually)
Insertion Sort
• Based on technique of card players to arrange a hand
• Player keeps cards picked up so far in sorted order
• When the player picks up a new card
• Makes room for the new card
• Then inserts it in its proper place
Insertion Sort Algorithm

• For each element from 2nd (nextPos = 1) to last:


• Insert element at nextPos where it belongs
• Increases sorted subarray size by 1

• To make room:
• Hold nextPos value in a variable
• Shuffle elements to the right until gap at right place
Insertion Sort Example
Analysis of Insertion Sort

• Maximum number of comparisons: O(n2)


• In the best case, number of comparisons: O(n)
• # shifts for an insertion = # comparisons - 1
• When new value smallest so far, #
comparisons
• A shift in insertion sort moves only one item
• Bubble or selection sort exchange: 3 assignments
Comparison of Quadratic Sorts
• None good for large arrays!
Shell Sort: A Better Insertion Sort

• Shell sort is a variant of insertion sort


• It is named after Donald Shell
• Average performance: O(n3/2) or better
• Divide and conquer approach to insertion sort
• Sort many smaller subarrays using insertion sort
• Sort progressively larger arrays
• Finally sort the entire array
• These arrays are elements separated by a gap
• Start with large gap
• Decrease the gap on each “pass”
Shell Sort: The Varying Gap

Before and after sorting with gap = 7

Before and after sorting with gap = 3


Analysis of Shell Sort
• Intuition:
Reduces work by moving elements farther earlier
• Its general analysis is an open research problem
• Performance depends on sequence of gap values
• For sequence 2k, performance is O(n2)
• Hibbard’s sequence (2k -1), performance is O(n3/2)
• We start with n/2 and repeatedly divide by 2.2
• Empirical results show this is O(n5/4) or O(n7/6)
• No theoretical basis (proof) that this holds
Shell Sort Algorithm

1. Set gap to n/2


2. while gap > 0
3. for each element from gap to end, by gap
4. Insert element in its gap-separated
sub-array
5. if gap is 2, set it to 1
6. otherwise set it to gap / 2.2
Shell Sort Algorithm: Inner Loop

3.1 set nextPos to position of element to insert


3.2 set nextVal to value of that element
3.3 while nextPos > gap and
element at nextPos-gap is > nextVal
3.4 Shift element at nextPos-gap to nextPos
3.5 Decrement nextPos by gap
3.6 Insert nextVal at nextPos
Merge Sort

• A merge is a common data processing operation:


• Performed on two sequences of data
• Items in both sequences use same compareTo
• Both sequences in ordered of this compareTo
• Goal: Combine the two sorted sequences in one
larger sorted sequence

• Merge sort merges longer and longer sequences


Merge Algorithm (Two Sequences)

Merging two sequences:


1. Access the first item from both sequences
2. While neither sequence is finished
1. Compare the current items of both
2. Copy smaller current item to the output
3. Access next item from that input sequence
3. Copy any remaining from first sequence to output
4. Copy any remaining from second to output
Picture of Merge
Analysis of Merge

• Two input sequences, total length n elements


• Must move each element to the output
• Merge time is O(n)

• Must store both input and output sequences


• An array cannot be merged in place
• Additional space needed: O(n)
Merge Sort Algorithm

Overview:
• Split array into two halves
• Sort the left half (recursively)
• Sort the right half (recursively)
• Merge the two sorted halves
Merge Sort Algorithm (2)
Detailed algorithm:
• if tSize £ 1, return (no sorting required)
• set hSize to tSize / 2
• Allocate LTab of size hSize
• Allocate RTab of size tSize – hSize
• Copy elements 0 .. hSize – 1 to LTab
• Copy elements hSize .. tSize – 1 to RTab
• Sort LTab recursively
• Sort RTab recursively
• Merge LTab and RTab into a
Merge Sort Example
Merge Sort Analysis
• Splitting/copying n elements to subarrays: O(n)
• Merging back into original array: O(n)
• Recursive calls: 2, each of size n/2
• Their total non-recursive work: O(n)
• Next level: 4 calls, each of size n/4
• Non-recursive work again O(n)
• Size sequence: n, n/2, n/4, ..., 1
• Number of levels = log n
• Total work: O(n log n)
Heapsort
• Merge sort time is O(n log n)
• But requires (temporarily) n extra storage items
• Heapsort
• Works in place: no additional storage
• Offers same O(n log n) performance
• Idea (not quite in-place):
• Insert each element into a priority queue
• Repeatedly remove from priority queue to array
• Array slots go from 0 to n-1
Heapsort Picture
Heapsort Picture (2)
Algorithm for In-Place Heapsort

• Build heap starting from unsorted array


• While the heap is not empty
• Remove the first item from the heap:
• Swap it with the last item
• Restore the heap property
Heapsort Analysis

• Insertion cost is log i for heap of size i


• Total insertion cost = log(n)+log(n-1)+...+log(1)
• This is O(n log n)
• Removal cost is also log i for heap of size i
• Total removal cost = O(n log n)

• Total cost is O(n log n)


Quicksort

• Developed in 1962 by C. A. R. Hoare


• Given a pivot value:
• Rearranges array into two parts:
• Left part £ pivot value
• Right part > pivot value
• Average case for Quicksort is O(n log n)
• Worst case is O(n2)
Quicksort Example
Algorithm for Quicksort
first and last are end points of region to sort
• if first < last
• Partition using pivot, which ends in pivIndex
• Apply Quicksort recursively to left subarray
• Apply Quicksort recursively to right subarray

Performance: O(n log n) provide pivIndex not always


too close to the end
Performance O(n2) when pivIndex always near end
Algorithm for Partitioning
1. Set pivot value to a[fst]
2. Set up to fst and down to lst
3. do
4. Increment up until a[up] > pivot or up = lst
5. Decrement down until a[down] <= pivot or
down = fst
6. if up < down, swap a[up] and a[down]
7. while up is to the left of down
8. swap a[fst] and a[down]
9. return down as piv Index
Trace of Algorithm for Partitioning
Revised Partitioning Algorithm

• Quicksort is O(n2) when each split gives 1 empty array


• This happens when the array is already sorted
• Solution approach: pick better pivot values
• Use three “marker” elements: first, middle, last
• Let pivot be one whose value is between the others
Testing Sorting Algorithms

• Need to use a variety of test cases


• Small and large arrays
• Arrays in random order
• Arrays that are already sorted (and reverse order)
• Arrays with duplicate values
• Compare performance on each type of array
Chapter Summary

• Three quadratic sorting algorithms:


• Selection sort, bubble sort, insertion sort
• Shell sort: good performance for up to 5000 elements
• Quicksort: average-case O(n log n)
• If the pivot is picked poorly, get worst case: O(n2)
• Merge sort and heapsort: guaranteed O(n log n)
• Merge sort: space overhead is O(n)
• Java API has good implementations
Chapter Summary (2)

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy