Sorting & Searching Geletaw S (MSC, MCITP). Objectives At the end of this session the students should be able to: – Design and implement the following.

Slides:



Advertisements
Similar presentations
Garfield AP Computer Science
Advertisements

CSE Lecture 3 – Algorithms I
Sorting A fundamental operation in computer science (many programs need to sort as an intermediate step). Many sorting algorithms have been developed Choose.
Data Structures and Algorithms
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.
the fourth iteration of this loop is shown here
CSE 373: Data Structures and Algorithms
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
Cmpt-225 Sorting. Fundamental problem in computing science  putting a collection of items in order Often used as part of another algorithm  e.g. sort.
CS 104 Introduction to Computer Science and Graphics Problems Data Structure & Algorithms (3) Recurrence Relation 11/11 ~ 11/14/2008 Yang Song.
Algorithm Efficiency and Sorting
1 © 2006 Pearson Addison-Wesley. All rights reserved Searching and Sorting Linear Search Binary Search ; Reading p Selection Sort ; Reading p
 2003 Prentice Hall, Inc. All rights reserved Sorting Arrays Sorting data –Important computing application –Virtually every organization must sort.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 11 Sorting and Searching.
Describing algorithms in pseudo code To describe algorithms we need a language which is: – less formal than programming languages (implementation details.
Fall 2013 Instructor: Reza Entezari-Maleki Sharif University of Technology 1 Fundamentals of Programming Session 17 These.
Week 11 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
Lecture 5 Searching and Sorting Richard Gesick. The focus Searching - examining the contents of the array to see if an element exists within the array.
Fall 2013 Instructor: Reza Entezari-Maleki Sharif University of Technology 1 Fundamentals of Programming Session 17 These.
CSCE 3110 Data Structures & Algorithm Analysis Sorting (I) Reading: Chap.7, Weiss.
Chapter 19: Searching and Sorting Algorithms
 Pearson Education, Inc. All rights reserved Searching and Sorting.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 19: Searching and Sorting.
Advance Data Structure 1 College Of Mathematic & Computer Sciences 1 Computer Sciences Department م. م علي عبد الكريم حبيب.
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.
CSE 373 Data Structures and Algorithms
Lecture 6 Sorting Algorithms: Bubble, Selection, and Insertion.
CSC 211 Data Structures Lecture 13
1 Today’s Material Iterative Sorting Algorithms –Sorting - Definitions –Bubble Sort –Selection Sort –Insertion Sort.
Sorting – Insertion and Selection. Sorting Arranging data into ascending or descending order Influences the speed and complexity of algorithms that use.
BUBBLE SORT. Introduction Bubble sort, also known as sinking sort, is a simple sorting algorithm that works by repeatedly stepping through the list to.
Chapter 5 Searching and Sorting. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-2 Chapter Objectives Examine the linear search and binary.
Data Structure Introduction.
Fundamentals of Algorithms MCS - 2 Lecture # 15. Bubble Sort.
Review 1 Arrays & Strings Array Array Elements Accessing array elements Declaring an array Initializing an array Two-dimensional Array Array of Structure.
Searching & Sorting Programming 2. Searching Searching is the process of determining if a target item is present in a list of items, and locating it A.
1 Sorting (Bubble Sort, Insertion Sort, Selection Sort)
Sorting and Searching. Selection Sort  “Search-and-Swap” algorithm 1) Find the smallest element in the array and exchange it with a[0], the first element.
Lecture No. 04,05 Sorting.  A process that organizes a collection of data into either ascending or descending order.  Can be used as a first step for.
1 Searching and Sorting Searching algorithms with simple arrays Sorting algorithms with simple arrays –Selection Sort –Insertion Sort –Bubble Sort –Quick.
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.
Searching and Sorting Searching: Sequential, Binary Sorting: Selection, Insertion, Shell.
Course Code #IDCGRF001-A 5.1: Searching and sorting concepts Programming Techniques.
Insertion Sort while some elements unsorted: Using linear search, find the location in the sorted portion where the 1 st element of the unsorted portion.
1. Searching The basic characteristics of any searching algorithm is that searching should be efficient, it should have less number of computations involved.
PREVIOUS SORTING ALGORITHMS  BUBBLE SORT –Time Complexity: O(n 2 ) For each item, make (n –1) comparisons Gives: Comparisons = (n –1) + (n – 2)
Chapter 9: Sorting1 Sorting & Searching Ch. # 9. Chapter 9: Sorting2 Chapter Outline  What is sorting and complexity of sorting  Different types of.
 2006 Pearson Education, Inc. All rights reserved. 1 Searching and Sorting.
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.
Searching and Sorting Searching algorithms with simple arrays
Growth of Functions & Algorithms
COMP108 Algorithmic Foundations Polynomial & Exponential Algorithms
Lecture 14 Searching and Sorting Richard Gesick.
Searching and Sorting Linear Search Binary Search ; Reading p
Linear and Binary Search
Objectives At the end of the class, students are expected to be able to do the following: Understand the purpose of sorting technique as operations on.
Describing algorithms in pseudo code
Sorting Algorithms IT12112 Lecture 07.
CSC215 Lecture Algorithms.
Lecture 11 Searching and Sorting Richard Gesick.
Sorting … and Insertion Sort.
Simple Sorting Methods: Bubble, Selection, Insertion, Shell
CSCE 3110 Data Structures & Algorithm Analysis
CSCE 3110 Data Structures & Algorithm Analysis
CSCE 3110 Data Structures & Algorithm Analysis
Algorithms.
Module 8 – Searching & Sorting Algorithms
Presentation transcript:

Sorting & Searching Geletaw S (MSC, MCITP)

Objectives At the end of this session the students should be able to: – Design and implement the following simple sorting algorithms: Bubble sort Insertion sort Selection sort – Compare the efficiency of the sorting algorithms in terms of Big-O complexity and space requirements to sort small number of elements. – Discuss the efficiency of the following simple searching algorithms: Sequential or linear search Binary search

What is Sorting? Sorting: an operation that segregates items into groups according to specified criterion. A = { } A = { }

Why Sort and Examples Consider: Sorting Books in Library Sorting Individuals by Height Sorting Movies in Best-seller Sorting Numbers (Sequential)

Types of Sorting Algorithms There are many, many different types of sorting algorithms, but the primary ones are: ● Bubble Sort ● Selection Sort ● Insertion Sort ● Merge Sort ● Shell Sort ● Heap Sort ● Quick Sort ● Radix Sort ● Swap Sort

Bubble Sort The simplest algorithm to implement The slowest algorithm on very large inputs. Basic Idea: – Loop through array from i=0 to n and swap adjacent elements if they are out of order.

Pseudo code Set flag = false 1.Traverse the array and compare pairs of two elements 1.1 If E1  E2 - OK 1.2 If E1 > E2 then Switch(E1, E2) and set flag = true 2.If flag = true goto 1.

Implementation void bubbleSort (Array S, length n) { boolean isSorted = false; while(!isSorted) { isSorted = true; for(i = 0; i<n; i++) { if(S[i] > S[i+1]) { int aux = S[i]; S[i] = S[i+1]; S[i+1] = aux; isSorted = false; }

Bubble Sort finish the first traversal start again finish the second traversal start again ---- ………………….

Analysis of Bubble Sort How many comparisons? – (n-1)+(n-2)+…+1= O(n 2 ) How many swaps? – (n-1)+(n-2)+…+1= O(n 2 )

Selection Sort How does it work: – first find the smallest in the array and exchange it with the element in the first position, – then find the second smallest element and exchange it with the element in the second position, and – continue in this way until the entire array is sorted.

Con’t… Selection sort is: – The simplest sorting techniques. – a good algorithm to sort a small number of elements – an incremental algorithm – induction method Selection sort is Inefficient for large lists. Incremental algorithms  process the input elements one- by-one and maintain the solution for the elements processed so far.

Selection Sort Algorithm Input: An array A[1..n] of n elements. Output: A[1..n] sorted in nondecreasing order. 1. for i  1 to n k  i 3. for j  i + 1 to n {Find the i th smallest element.} 4. if A[j] < A[k] then k  j 5. end for 6. if k  i then interchange A[i] and A[k] 7. end for

Example Original array: st pass -> (2 and 6 were swapped) 2nd pass -> (4 and 5 were swapped) 3rd pass -> (6 and 9 were swapped) 4th pass -> (7 and 9 were swapped) 5th pass -> (no swap) 6th pass -> (no swap)

Analysis of Algorithms Algorithm analysis: quantify the performance of the algorithm, i.e., the amount of time and space taken in terms of n. T(n) is the total number of accesses made from the beginning of selection_sort until the end. selection_sort itself simply calls swap and find_min_index as i goes from 1 to n-1 = n-1 + n-2 + n-3 + … + 1 = n(n-1)/2 Or = ∑ (n - i) = n (n - 1) / 2 -  O(n 2 )

Insertion Sort Insertion sort keeps making the left side of the array sorted until the whole array is sorted.

Insertion Sort while some elements unsorted: – Using linear search, find the location in the sorted portion where the 1 st element of the unsorted portion should be inserted – Move all the elements after the insertion location up one position to make space for the new element

An insertion sort partitions the array into two regions

Example: sorting numbered cards Given some numbered cards. Our aim is to put them into nondecreasing order.

Example: sorting numbered cards

Example: sorting numbered cards

Example: sorting numbered cards

Example: sorting numbered cards

Example: sorting numbered cards

Example: sorting numbered cards

Example: sorting numbered cards

Algorithm: INSERTIONSORT Input: An array A[1..n] of n elements. Output: A[1..n] sorted in nondecreasing order. 1. for i  2 to n 2. x  A[i] 3. j  i while (j >0) and (A[j] > x) 5. A[j + 1]  A[j] 6. j  j end while 8. A[j + 1]  x 9. end for

An insertion sort of an array of five integers

Con’t…. Algorithm Detail A[i] is inserted in its proper position in the ith iteration in the sorted subarray A[1.. i-1] In the ith step, the elements from index i-1 down to 1 are scanned, each time comparing A[i] with the element at the correct position. In each iteration an element is shifted one position up to a higher index. The process of comparison and shifting continues until: – Either an element ≤ A[i] is found or – When all the sorted sequence so far is scanned. Then A[i] is inserted in its proper position.

Analysis Let a 0,..., a n-1 be the sequence to be sorted. At the beginning and after each iteration of the algorithm the sequence consists of two parts: the first part a 0,..., a i-1 is already sorted, the second part a i,..., a n-1 is still unsorted (i in 0,..., n). The worst case occurs when in every step the proper position for the element that is inserted is found at the beginning of the sorted part of the sequence.

Searching Definition – The process of finding a particular element of an array Types of Search Sequential or linear search Binary search Why Search & Examples – Looking up a phone number – Accessing a Web site and – Checking the definition of a word in a dictionary

Linear Search (Sequential Search) Algorithm Each element of an array is read one by one sequentially and it is compared with the search key. Let A be an array of having n elements, A[0],A[1],A[2], A[n-1]. “item” is the element to be searched. Then this algorithm will find the location “loc” of item in A. Set loc = – 1, if the search is unsuccessful.

Con’t…. 1.Input an array A of n elements and “item” to be searched and initialize loc = – 1. 2.Initialise i = 0; and repeat through step 3 if (i < n) by incrementing i by one. 3.If (item = A[i]) loc = i GOTO step 4 4. If (loc >= 0) Display “item is found and searching is successful” 5. else Display “item is not found and searching is unsuccessful” 6. exit

Efficiency of Linear Search – The linear search algorithm runs in O(n) time

Example for implementation int Linear_Search(int list[], int key) { int index=0; int found=0; Do { if(key==list[index]) found=1; else index++; }while(found==0&&index<n); if(found==0) index=-1; return index; }

Binary Search algorithm Binary search is an extremely efficient algorithm when it is compared to linear search. Binary search technique searches “item” in minimum possible comparisons. Assumption – the given array is a sorted one, otherwise first we have to sort the array elements.

Con’t…. 1.Find the middle element of the array (i.e., n/2 is the middle element if the array or the sub-array contains n elements). 2.Compare the middle element with the data to be searched, and then there are following three cases. a.If it is a desired element, then search is successful. b.If it is less than desired data, then search only the first half of the array, i.e. the elements which come to the left side of the middle element. c.If it is greater than the desired data, then search only the second half of the array, i.e., the elements which come to the right side of the middle element. 3.Repeat the same step until an element is found or exhaust the search area.

Efficiency The computational time for this algorithm is proportional to log 2 n,Therefore the time complexity is O(log n)

Example for Implementation int Binary_Search(int list[],int k) { int left=0; int right=n-1; int found=0; do{ mid=(left+right)/2; if(key==list[mid]) found=1; Else { if(key<list[mid]) right=mid-1; else left=mid+1; } }while(found==0&&left<right); if(found==0) index=-1; else index=mid; return index; }

Individual Assignment Write a program for sorting (bubble, insertion, selection) and searching (linear, binary) algorithm? Hint: Menu 1.Sorting 1.Bubble 2.Selection 3.Insertion 2.Searching 1.Linear 2.Binary Criteria for Evaluation Running time Proper Indentation Proper Declaration and Function usage