Sorting and Searching Algorithms

Slides:



Advertisements
Similar presentations
Garfield AP Computer Science
Advertisements

HST 952 Computing for Biomedical Scientists Lecture 9.
Using Divide and Conquer for Sorting
Heapsort By: Steven Huang. What is a Heapsort? Heapsort is a comparison-based sorting algorithm to create a sorted array (or list) Part of the selection.
Sorting Chapter Sorting Consider list x 1, x 2, x 3, … x n We seek to arrange the elements of the list in order –Ascending or descending Some O(n.
Sorting Part 3 CS221 – 3/6/09. Sort Matrix NameWorst Time Complexity Average Time Complexity Best Time Complexity Worst Space (Auxiliary) Selection SortO(n^2)
Chapter 11 Sorting and Searching. Copyright © 2005 Pearson Addison-Wesley. All rights reserved Chapter Objectives Examine the linear search and.
CHAPTER 11 Sorting.
C++ Plus Data Structures
CHAPTER 7: SORTING & SEARCHING Introduction to Computer Science Using Ruby (c) Ophir Frieder at al 2012.
C# Advanced Topics Methods, Classes and Objects SoftUni Team Technical Trainers Software University
Advanced Tree Structures
Software Testing Lifecycle Exit Criteria Evaluation, Continuous Integration Ivan Yonkov Technical Trainer Software University.
Fall 2013 Instructor: Reza Entezari-Maleki Sharif University of Technology 1 Fundamentals of Programming Session 17 These.
Merge Sort. What Is Sorting? To arrange a collection of items in some specified order. Numerical order Lexicographical order Input: sequence of numbers.
Loops Repeating Code Multiple Times SoftUni Team Technical Trainers Software University
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 19: Searching and Sorting.
LAB#7. Insertion sort In the outer for loop, out starts at 1 and moves right. It marks the leftmost unsorted data. In the inner while loop, in starts.
1 Joe Meehean.  Problem arrange comparable items in list into sorted order  Most sorting algorithms involve comparing item values  We assume items.
Svetlin Nakov Technical Trainer Software University
Build Processes and Continuous Integration Automating Build Processes Software University Technical Trainers SoftUni Team.
Sorting. Pseudocode of Insertion Sort Insertion Sort To sort array A[0..n-1], sort A[0..n-2] recursively and then insert A[n-1] in its proper place among.
Multidimensional Arrays, Sets, Dictionaries Processing Matrices, Multidimensional Arrays, Dictionaries, Sets SoftUni Team Technical Trainers Software University.
© M. Gross, ETH Zürich, 2014 Informatik I für D-MAVT (FS 2014) Exercise 12 – Data Structures – Trees Sorting Algorithms.
Test-Driven Development Learn the "Test First" Approach to Coding SoftUni Team Technical Trainers Software University
Chapter 5 Searching and Sorting. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-2 Chapter Objectives Examine the linear search and binary.
Sorting Chapter Sorting Consider list x 1, x 2, x 3, … x n We seek to arrange the elements of the list in order –Ascending or descending Some O(n.
Comparison of Optimization Algorithms By Jonathan Lutu.
Graphs and Graph Algorithms Fundamentals, Terminology, Traversal, Algorithms SoftUni Team Technical Trainers Software University
Arrays, Lists, Stacks, Queues Processing Sequences of Elements SoftUni Team Technical Trainers Software University
1 C++ Plus Data Structures Nell Dale Chapter 10 Sorting and Searching Algorithms Slides by Sylvia Sorkin, Community College of Baltimore County - Essex.
Very Basic Mathematical Concepts for Programmers
Java Methods Big-O Analysis of Algorithms Object-Oriented Programming
Review 1 Selection Sort Selection Sort Algorithm Time Complexity Best case Average case Worst case Examples.
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.
© 2004 Goodrich, Tamassia Quick-Sort     29  9.
Exam Preparation Algorithms Course: Sample Exam SoftUni Team Technical Trainers Software University
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.
Data Structures and Algorithms Searching Algorithms M. B. Fayek CUFE 2006.
ICS201 Lecture 21 : Sorting King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department.
Selection Sort main( ) { int a[ ] = { 17, 6, 13,12, 2 } ; int i, j, t ; for ( i = 0 ; i
Parallel Programming - Sorting David Monismith CS599 Notes are primarily based upon Introduction to Parallel Programming, Second Edition by Grama, Gupta,
Mocking with Moq Tools for Easier Unit Testing SoftUni Team Technical Trainers Software University
Chapter 9: Sorting1 Sorting & Searching Ch. # 9. Chapter 9: Sorting2 Chapter Outline  What is sorting and complexity of sorting  Different types of.
Sorting & Searching Geletaw S (MSC, MCITP). Objectives At the end of this session the students should be able to: – Design and implement the following.
329 3/30/98 CSE 143 Searching and Sorting [Sections 12.4, ]
Processing Sequences of Elements
Sets, Dictionaries SoftUni Team Technical Trainers Software University
SoftUni Team Technical Trainers Software University Trees and Tree-Like Structures Trees, Tree-Like Structures, Binary Search Trees,
Data Structures and Algorithms Telerik Software Academy
Advanced Tree Structures Binary Trees, AVL Tree, Red-Black Tree, B-Trees, Heaps SoftUni Team Technical Trainers Software University
INTRO2CS Tirgul 8 1. Searching and Sorting  Tips for debugging  Binary search  Sorting algorithms:  Bogo sort  Bubble sort  Quick sort and maybe.
Functional Programming Data Aggregation and Nested Queries Ivan Yonkov Technical Trainer Software University
1 compares each element of the array with the search key. works well for small arrays or for unsorted arrays works for any table slow can put more commonly.
Inheritance Class Hierarchies SoftUni Team Technical Trainers Software University
Stacks and Queues Processing Sequences of Elements SoftUni Team Technical Trainers Software University
Generics SoftUni Team Technical Trainers Software University
Priority Queues and Heaps. John Edgar  Define the ADT priority queue  Define the partially ordered property  Define a heap  Implement a heap using.
Sorting and Searching Algorithms
Heaps and Priority Queues
Balancing Binary Search Trees, Rotations
Fast String Manipulation
Array and List Algorithms
Description Given a linear collection of items x1, x2, x3,….,xn
CSC215 Lecture Algorithms.
8/04/2009 Many thanks to David Sun for some of the included slides!
Searching CLRS, Sections 9.1 – 9.3.
Presentation transcript:

Sorting and Searching Algorithms Sorting, Searching, Shuffling Sorting and Searching SoftUni Team Technical Trainers Software University http://softuni.bg © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

Table of Contents Sorting Searching Shuffling Algorithms Types of Sorting Algorithms Popular Sorting Algorithms Searching Linear Search Binary Search Interpolation Search Shuffling Algorithms © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

Sorting

What is a Sorting Algorithm? An algorithm that rearranges elements in a list In non-decreasing order Elements must be comparable More formally The input is a sequence / list of elements The output is an rearrangement / permutation of elements

Sorting – Example Efficient sorting algorithms are important for Producing human-readable output Canonicalizing data – making data uniquely arranged In conjunction with other algorithms, like binary searching Example of sorting: Unsorted list sorting Sorted list 10 3 7 4 3 4 7 10

Sorting Algorithms: Classification Sorting algorithms are often classified by Computational complexity and memory usage Worst, average and best case behavior Recursive / non-recursive Stability – stable / unstable Comparison-based sort / non-comparison based Sorting method: insertion, exchange (bubble sort and quicksort), selection (heapsort), merging, serial / parallel, etc.

Stability of Sorting Stable sorting algorithms Maintain the order of equal elements If two items compare as equal, their relative order is preserved Unstable sorting algorithms Rearrange the equal elements in unpredictable order Often different elements have same key used for equality comparing

Selection Sort Selection sort – simple, but inefficient algorithm (visualize) Swap the first with min element on the right, then the second, etc. Best, worst and average case: O(n2) Memory: O(1) Stable: No Method: Selection for (left = 0; left < n-1; left++) { // Find the min element in the unsorted range arr[left … n-1] minIndex = left; for (i = left + 1; i < n; i++) if (arr[i] < arr[minIndex]) minIndex = i; if (minIndex != left) Swap(arr[left], arr[minIndex]); }

Selection Sort: Why Unstable? Why the "selection sort" is unstable? Swaps the first element with the min element on the right Swaps the second element with the min element on the right … During the swaps equal elements can jump over each other left min swap equal elements changed order 3♥ 5♠ 3♦ 4♥ 2♣ 3♥ 5♠ 3♦ 4♥ 2♣ 2♣ 5♠ 3♦ 4♥ 3♥

Bubble Sort Bubble sort – simple, but inefficient algorithm (visualize) Swaps to neighbor elements when not in order until sorted Best case: O(n); worst & average: O(n2) Memory: O(1) Stable: Yes Method: Exchanging do   swapped = false   for i = 1 to indexOfLastUnsortedElement     if leftElement > rightElement       Swap(leftElement, rightElement)       swapped = true while swapped

Insertion Sort Insertion sort – simple, but inefficient algorithm (visualize) Move the first unsorted element left to its place Best case: O(n); worst & average: O(n2) Memory: O(1) Stable: Yes Method: Insertion for firstUnsortedIndex = 1 to length(arr) – 1 { i = firstUnsortedIndex while (i > 0 && arr[i-1] > arr[i]) { Swap(arr[i], arr[i-1]) i-- }

QuickSort QuickSort – efficient sorting algorithm (visualize) Choose a pivot; move smaller elements left & larger right; sort left & right Best & average case: O(n*log(n)); Worst: O(n2) Memory: O(log(n)) stack space (for recursion) Stable: Depends Method: Partitioning QuickSort(arr, lo, hi) if lo < hi p = Partition(arr, lo, hi) QuickSort(arr, lo, p) // sort the left partition QuickSort(arr, p + 1, hi) // sort thr right partition

QuickSort: Partitioning Partition(arr, lo, hi) pivot = arr[lo] left = lo - 1 right = hi + 1 while (true) do right-- while arr[right] > pivot left++ while arr[left] < pivot if left < right Swap(arr[left], arr[right]) else return right

Merge Sort Merge sort is efficient sorting algorithm (visualize) Divide the list into sub-lists (typically 2 sub-lists) Sort each sub-list (recursively call merge-sort) Merge the sorted sub-lists into a single list Best, average and worst case: O(n*log(n)) Memory: Typically O(n) With in-place merge can be O(1) Highly parallelizable on multiple cores / machines  up to O(log(n) Stable: Yes Method: Merging

Merge Sort: Hot It Works?

Merge Sort: Pseudocode MergeSort(list) var len = length(list) if len <= 1 return list // List already sorted var middle = len / 2 var left = SubList(list, 0, middle) var right = SubList(list, middle + 1, len-1) left = MergeSort(left) right = MergeSort(right) return Merge(left, right)

Merge: Pseudocode Merge(leftList, rightList) var mergedlist = new list[length(leftList) + length(rightList)] var leftIndex, rightIndex, mergedIndex = 0 while (leftIndex < length(left) && rightIndex < length(rightList) if (leftList[leftIndex] < rightList[rightIndex]) mergedList[mergedIndex++] = leftList[leftIndex++]; else mergedList[mergedIndex++] = rightList[rightIndex++]; while (leftIndex < leftList.Length) while (rightIndex < rightList.Length) return mergedList;

Heap Data Structure Heap == tree-based data structure that satisfies the heap property: Parent nodes are always greater than or equal to the children No implied ordering between siblings or cousins Binary heap visualization: http://visualgo.net/heap.html Find-min Θ(1) Delete-min Θ(log n) Insert Decrease-key Merge Θ(n)

HeapSort HeapSort works in two phases (visualize): A heap is built out of the array elements  O(n) A sorted array is created by removing the largest element from the heap n times  n * O(log n) Best, average and worst case: O(n*log(n)) Memory: O(1) – if the array and heap share the same memory Stable: No Method: Selection

Counting Sort Counting sort is very efficient sorting algorithm (visualize) Sorts small integers by counting their occurrences Not a comparison-based sort Best, average and worst case: O(n + r) r is the range of numbers to be sorted E.g. [-1000 ... 1000]  r = 2001 Memory: O(n + r) Stable: Yes Method: Counting

Bucket Sort Bucket sort partitions an array into a number of buckets Each bucket is then sorted individually Not a comparison-based sort Average case: O(n + k) k = the number of buckets Worst case: O(n * log n) Stable: Yes Memory: O(n) – n buckets holding n elements totally

Comparison of Sorting Algorithms Name Best Average Worst Memory Stable Method SelectionSort n2 1 No Selection BubbleSort n Yes Exchanging InsertionSort Insertion QuickSort n*log(n) log(n) Depends Partitioning MergeSort 1 (or n) Merging HeapSort BogoSort n*n! Luck

Searching Algorithms

Search Algorithm Search algorithm == an algorithm for finding an item with specified properties among a collection of items Different types of searching algorithms For virtual search spaces Satisfy specific mathematical equations Try to exploit partial knowledge about a structure For sub-structures of a given structure A graph, a string, a finite group Search for the min / max of a function, etc.

Linear Search Linear search finds a particular value in a list (visualize) Checking every one of the elements One at a time, in sequence Until the desired one is found Worst & average performance: O(n) for each item in the list: if that item has the desired value, return the item's location return nothing

Binary Search Binary search finds an item within a ordered data structure At each step, compare the input with the middle element The algorithm repeats its action to the left or right sub-structure Average performance: O(log(n)) See the visualization

Binary Search (Recursive) int BinarySearch(int arr[], int key, int start, int end) { if (end < start) return KEY_NOT_FOUND; else { int mid = (start + end) / 2; if (arr[mid] > key) return BinarySearch(arr, key, start, mid - 1); else if (arr[mid] < key) return BinarySearch(arr, key, mid + 1, end); else return mid; }

Binary Search (Iterative) int BinarySearch(int arr[], int key, int start, int end) { while (end >= start) { int mid = (start + end) / 2; if (arr[mid] < key) start = mid + 1; else if (arr[mid] > key) end = mid - 1; else return mid; } return KEY_NOT_FOUND;

Interpolation Search Interpolation search == an algorithm for searching for a given key in an ordered indexed array Parallels how humans search through a telephone book Calculates where in the remaining search space the item might be Binary search always chooses the middle element Can we have a better hit, e.g. Angel in the phonebook should be at the start, not at the middle, OK? Average case: log(log(n)), Worst case: O(n) http://youtube.com/watch?v=l1ed_bTv7Hw

Interpolation Search – Sample Implementation int InterpolationSearch(int[] sortedArray, int key) { int low = 0; int high = sortedArray.Length - 1; while (sortedArray[low] <= key && sortedArray[high] >= key) { int mid = low + ((key - sortedArray[low]) * (high - low)) / (sortedArray[high] - sortedArray[low]); if (sortedArray[mid] < key) low = mid + 1; else if (sortedArray[mid] > key) high = mid - 1; else return mid; } if (sortedArray[low] == key) return low; else return KEY_NOT_FOUND;

Shuffling Algorithms

Shuffling Shuffling == randomizing the order of items in a collection Generate a random permutation http://en.wikipedia.org/wiki/Shuffling

Fisher–Yates Shuffle Algorithm public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> source) { Random rnd = new Random(); var array = source.ToArray(); var n = array.Length; for (var i = 0; i < n; i++) // Exchange array[i] with random element in array[i … n-1] int r = i + rnd.Next(0, n - i); var temp = array[i]; array[i] = array[r]; array[r] = temp; } return array; Shuffle algorithms: visualization

Summary Slow sorting algorithms: Fast sorting algorithms: Selection sort, Bubble sort, Insertion sort Fast sorting algorithms: Quick sort, Merge sort, Heap sort, Counting sort, Bucket sort Searching algorithms: Unsorted list  linear search (slow) Sorted list  binary search / interpolation search (fast) Fisher–Yates algorithm shuffles array in linear time © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

Sorting and Searching Algorithms https://softuni.bg/trainings/1194/Algorithms-September-2015 © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

License This course (slides, examples, labs, videos, homework, etc.) is licensed under the "Creative Commons Attribution- NonCommercial-ShareAlike 4.0 International" license Attribution: this work may contain portions from "Fundamentals of Computer Programming with C#" book by Svetlin Nakov & Co. under CC-BY-SA license "Data Structures and Algorithms" course by Telerik Academy under CC-BY-NC-SA license © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

Free Trainings @ Software University Software University Foundation – softuni.org Software University – High-Quality Education, Profession and Job for Software Developers softuni.bg Software University @ Facebook facebook.com/SoftwareUniversity Software University @ YouTube youtube.com/SoftwareUniversity Software University Forums – forum.softuni.bg © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.