Download presentation
Presentation is loading. Please wait.
Published byVirginia Dennis Modified over 9 years ago
1
Chapter 8 Sorting and Searching Goals: 1.Java implementation of sorting algorithms 2.Selection and Insertion Sorts 3.Recursive Sorts: Mergesort and Quicksort 4.Sequential search and binary search.
2
Selection Sort Search and swap algorithm – Algorithm Find smallest element Exchange it with the first position Repeat the above steps for the second, third, and other positions until array sorted. Example: – 8146 – 1 84 6 //1 st pass – 1 486 //2 nd pass – 1 468 // 3 rd pass
3
Selection Sort For an array of n elements, the array is sorted after n – 1 passes. Best case scenario array is sorted Worst case scenario all elements has to be changed or swapped. Inefficient for very large number arrays
4
Insertion Algorithm – Think of the 1 st element being sorted. – Compare the next element with the sorted one – Insert it if need causing all elements to move to the open empty space. – Repeat process for the next element by thinking of the first two elements being sorted. Insert if necessary.
5
Example Insertion Sort 81 46 //Start by saying 8 is sorted 1846 //first pass Insert 1 by comparing to 8 1 486 //second pass Insert 4 by comparing to 1 & 8 1 468 //third pass Insert 6 Notes: 1.For an array of n elements, the array is sorted after n-1 runs. 2.After the kth pass, a[0],a[1],….,a[k] are sorted with respect to each other but not necessarily in their final position 3.The worst case for insertion sort occurs if the array is initially sorted in reverse order, since this will lead to the max possible number of comparisons and moves. 4.The Best case for insertion sort occurs if the array is already sorted.
6
Merge Sort – Recursive Sort Divide and conquer more efficient than Insertion and Selection sorts. Merge Sort Algorithm – Break Array in to two halves – Mergesort the left half and MergeSort the right half by breaking them in half and keep repeating process until down to single element – Merge the single elements to form subarrays and merge subarrays until you get back to single Array
7
Merge Sort Example 5-32406 5-32406406 5-3240406 5-340 -35 0404 -325046046 -302456
8
Analysis of MergeSort The major disadvantage of mergeSort is that it needs temporary array that is as large as the original array to be sorted. Mergesort is not affected by the initial ordering of the elements. Thus best, worst and average cases have similar run times.
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.