Searching. The process used to find the location of a target among a list of objects Searching an array finds the index of first element in an array containing.

Slides:



Advertisements
Similar presentations
Binary Search lo Binary search. Given a key and sorted array a[], find index i such that a[i] = key,
Advertisements

Stephen P. Carl - CS 2421 Recursive Sorting Algorithms Reading: Chapter 5.
DIVIDE AND CONQUER APPROACH. General Method Works on the approach of dividing a given problem into smaller sub problems (ideally of same size).  Divide.
Sorting Algorithms and Average Case Time Complexity
Data Structures and Algorithms
Insertion sort, Merge sort COMP171 Fall Sorting I / Slide 2 Insertion sort 1) Initially p = 1 2) Let the first p elements be sorted. 3) Insert the.
Insertion sort, Merge sort COMP171 Fall Sorting I / Slide 2 Insertion sort 1) Initially p = 1 2) Let the first p elements be sorted. 3) Insert the.
Simple Sorting Algorithms
1 TCSS 342, Winter 2005 Lecture Notes Sorting Weiss Ch. 8, pp
Searching Arrays. COMP104 Lecture 22 / Slide 2 Unordered Linear Search * Search an unordered array of integers for a value and return its index if the.
TDDB56 DALGOPT-D DALG-C Lecture 8 – Sorting (part I) Jan Maluszynski - HT Sorting: –Intro: aspects of sorting, different strategies –Insertion.
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.
Algorithm Efficiency and Sorting
Sorting Algorithms Bubble Sort Merge Sort Quick Sort Randomized Quick Sort.
CSE 373 Data Structures Lecture 19
Simple Sorting Algorithms. 2 Bubble sort Compare each element (except the last one) with its neighbor to the right If they are out of order, swap them.
Simple Sorting Algorithms. 2 Outline We are going to look at three simple sorting techniques: Bubble Sort, Selection Sort, and Insertion Sort We are going.
Sorting Text Read Shaffer, Chapter 7 Sorting O(N 2 ) sorting algorithms: – Insertion, Selection, Bubble O(N log N) sorting algorithms – HeapSort, MergeSort,
1 1-d Arrays. 2 Array Many applications require multiple data items that have common characteristics  In mathematics, we often express such groups of.
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.
Sorting Algorithms. Sorting Sorting is a process that organizes a collection of data into either ascending or descending order. public interface ISort.
CS 162 Intro to Programming II Searching 1. Data is stored in various structures – Typically it is organized on the type of data – Optimized for retrieval.
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.
Lecture 6 Sorting Algorithms: Bubble, Selection, and Insertion.
Functions-Recall 1. 2 Parameter passing & return void main() { int x=10, y=5; printf (“M1: x = %d, y = %d\n”, x, y); interchange (x, y); printf (“M2:
Sorting – Insertion and Selection. Sorting Arranging data into ascending or descending order Influences the speed and complexity of algorithms that use.
Data Structure Introduction.
Sorting CSIT 402 Data Structures II. 2 Sorting (Ascending Order) Input ›an array A of data records ›a key value in each data record ›a comparison function.
Sort Algorithms.
LAB#6. 2 Overview Before we go to our lesson we must know about : 1. data structure. 2.Algorithms. data structure is an arrangement of data in a computer.
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.
CS 162 Intro to Programming II Bubble Sort 1. Compare adjacent elements. If the first is greater than the second, swap them. Do this for each pair of.
Lecture #9: Sorting Algorithms خوارزميات الترتيب Dr. Hmood Al-Dossari King Saud University Department of Computer Science 22 April 2012.
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.
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.
Analysis of Algorithms Asymptotic Performance. Review: Asymptotic Performance Asymptotic performance: How does algorithm behave as the problem size gets.
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.
2IS80 Fundamentals of Informatics Fall 2015 Lecture 6: Sorting and Searching.
Selection Sort main( ) { int a[ ] = { 17, 6, 13,12, 2 } ; int i, j, t ; for ( i = 0 ; i
PREVIOUS SORTING ALGORITHMS  BUBBLE SORT –Time Complexity: O(n 2 ) For each item, make (n –1) comparisons Gives: Comparisons = (n –1) + (n – 2)
1 Sorting. 2 Sorting Data Items Consider a set of data items  Each item may have more than one field Example: a student record with name, roll no, CGPA,…
Today’s Material Sorting: Definitions Basic Sorting Algorithms
Sorting Ordering data. Design and Analysis of Sorting Assumptions –sorting will be internal (in memory) –sorting will be done on an array of elements.
CS 367 Introduction to Data Structures Lecture 11.
Sorting & Searching Geletaw S (MSC, MCITP). Objectives At the end of this session the students should be able to: – Design and implement the following.
 Introduction to Search Algorithms  Linear Search  Binary Search 9-2.
1 Overview Divide and Conquer Merge Sort Quick Sort.
329 3/30/98 CSE 143 Searching and Sorting [Sections 12.4, ]
Sorting Algorithms. Sorting Sorting is a process that organizes a collection of data into either ascending or descending order. public interface ISort.
APPLICATIONS OF RECURSION Copyright © 2006 Pearson Addison-Wesley. All rights reserved
Sorting Mr. Jacobs.
COP 3503 FALL 2012 Shayan Javed Lecture 16
Lecture 14 Searching and Sorting Richard Gesick.
Simple Sorting Algorithms
Applications of Recursion
Advanced Sorting Methods: Shellsort
Selection sort Given an array of length n,
CSC215 Lecture Algorithms.
Lecture 11 Searching and Sorting Richard Gesick.
Searching: linear & binary
Binary Search Binary search. Given value and sorted array a[], find index i such that a[i] = value, or report that no such index exists. Invariant.
Sorting.
CSE 332: Data Abstractions Sorting I
Simple Sorting Algorithms
CSE 373 Data Structures and Algorithms
Simple Sorting Algorithms
Simple Sorting Algorithms
Advanced Sorting Methods: Shellsort
Presentation transcript:

Searching

The process used to find the location of a target among a list of objects Searching an array finds the index of first element in an array containing that value Searching

Unordered Linear Search Search an unordered array of integers for a value and return its index if the value is found. Otherwise, return -1. A[0] A[1] A[2] A[3] A[4] A[5] A[6] A[7] Algorithm: Start with the first array element (index 0) while(more elements in array){ if value found at current index, return index; Try next element (increment index); } Value not found, return -1;

Unordered Linear Search // Searches an unordered array of integers int search(int data[], //input: array int size, //input: array size int value){ //input: search value // output: if found, return index; // otherwise, return –1. for(int index = 0; index < size; index++){ if(data[index] == value) return index; } return -1; }

Binary Search lo Binary search. Given value and sorted array a[], find index i such that a[i] = value, or report that no such index exists. Invariant. Algorithm maintains a[lo]  value  a[hi]. Ex. Binary search for 33. hi

Binary Search Binary search. Given value and sorted array a[], find index i such that a[i] = value, or report that no such index exists. Invariant. Algorithm maintains a[lo]  value  a[hi]. Ex. Binary search for lo hi mid

Binary Search Binary search. Given value and sorted array a[], find index i such that a[i] = value, or report that no such index exists. Invariant. Algorithm maintains a[lo]  value  a[hi]. Ex. Binary search for lo hi

Binary Search Binary search. Given value and sorted array a[], find index i such that a[i] = value, or report that no such index exists. Invariant. Algorithm maintains a[lo]  value  a[hi]. Ex. Binary search for lo midhi

Binary Search Binary search. Given value and sorted array a[], find index i such that a[i] = value, or report that no such index exists. Invariant. Algorithm maintains a[lo]  value  a[hi]. Ex. Binary search for lohi

Binary Search Binary search. Given value and sorted array a[], find index i such that a[i] = value, or report that no such index exists. Invariant. Algorithm maintains a[lo]  value  a[hi]. Ex. Binary search for lohimid

Binary Search Binary search. Given value and sorted array a[], find index i such that a[i] = value, or report that no such index exists. Invariant. Algorithm maintains a[lo]  value  a[hi]. Ex. Binary search for lo hi

Binary Search Binary search. Given value and sorted array a[], find index i such that a[i] = value, or report that no such index exists. Invariant. Algorithm maintains a[lo]  value  a[hi]. Ex. Binary search for lo hi mid

Binary Search Binary search. Given value and sorted array a[], find index i such that a[i] = value, or report that no such index exists. Invariant. Algorithm maintains a[lo]  value  a[hi]. Ex. Binary search for lo hi mid

17 Example: Binary Search Searching for an element k in a sorted array A with n elements Idea: n Choose the middle element A[n/2] n If k == A[n/2], we are done n If k < A[n/2], search for k between A[0] and A[n/2 - 1] n If k > A[n/2], search for k between A[n/2 + 1] and A[n-1] n Repeat until either k is found, or no more elements to search Requires less number of comparisons than linear search in the worst case (log 2 n instead of n)

18 int main() { int A[100], n, k, i, mid, low, high; scanf(“%d %d”, &n, &k); for (i=0; i<n; ++i) scanf(“%d”, &A[i]); low = 0; high = n – 1; mid = (high + low)/2; while (high >= low) { if (A[mid] == k) { printf(“%d is found\n”, k); break; } if (k < A[mid]) high = mid – 1; else low = mid + 1; mid = (high + low)/2; } If (high < low) printf(“%d is not found\n”, k); }

Sorting

20 Bubble Sort Stage 1: Compare each element (except the last one) with its neighbor to the right n If they are out of order, swap them n This puts the largest element at the very end n The last element is now in the correct and final place Stage 2: Compare each element (except the last two) with its neighbor to the right n If they are out of order, swap them n This puts the second largest element next to last n The last two elements are now in their correct and final places Stage 3: Compare each element (except the last three) with its neighbor to the right n Continue as above until you have no unsorted elements on the left

21 Example of Bubble Sort (done) Stage 1Stage 2Stage 3 Stage 4

22 Code for Bubble Sort void bubbleSort(int[] a) { int stage, inner, temp; for (stage = a.length - 1; stage > 0; stage--) { // counting down for (inner = 0; inner a[inner + 1]) { // if out of order... temp = a[inner]; //...then swap a[inner] = a[inner + 1]; a[inner + 1] = temp; } } } }

23 Insertion Sort

24 Insertion Sort Suppose we know how to insert a new element x in its proper place in an already sorted array A of size k, to get a new sorted array of size k+1 Use this to sort the given array A of size n as follows: n Insert A[1] in the sorted array A[0]. So now A[0],A[1] are sorted n Insert A[2] in the sorted array A[0],A[1]. So now A[0],A[1],A[2] are sorted n Insert A[3] in the sorted array A[0],A[1],A[2]. So now A[0],A[1],A[2],A[3] are sorted n ….. n Insert A[i] in the sorted array A[0],A[1],…,A[i-1]. So now A[0],A[1],…A[i] are sorted n Continue until i = n-1 (outer loop)

25 How to do the first step Compare x with A[k-1] (the last element) n If x ≥ A[k-1], we can make A[k] = x (as x is the max of all the elements) n If x < A[k-1], put A[k] = A[k-1] to create a hole in the k-th position, put x there Now repeat by comparing x with A[k-2] (inserting x in its proper place in the sorted subarray A[0],A[1],…A[k-1] of k-2 elements) The value x bubbles to the left until it finds an element A[i] such that x ≥ A[i] No need to compare any more as all elements A[0], A[1], A[i] are less than x

26 Example of first step AInsert x = 15

27 Example of first step AInsert x = 15 Compare with 22. x < 22, so move 22 right

28 Example of first step AInsert x = 15 Compare with 22. x < 22, so move 22 right Compare with 20. x < 20, so move 20 right

29 Example of first step AInsert x = 15 Compare with 22. x < 22, so move 22 right Compare with 20. x < 20, so move 20 right Compare with 13. x > 13, so stop A

30 Sort using the insertion A Insert 5 in 7 Insert 13 in 5, 7 Insert 11 in 5, 7, 13 Insert 22 in 5, 7, 11, 13 Insert 20 in 5, 7, 11, 13,

31 Insertion Sort Code void InsertionSort (int A[ ], int size) { int i, j, item; for (i=1; i<size; i++) { /* Insert the element in A[i] */ item = A[i] ; for (j = i-1; j >= 0; j--) if (item < A[j]) { /* push elements down*/ A[j+1] = A[j]; A[j] = item ; /* can do this once finally also */ } else break; /*inserted, exit loop */ }

32 Look at the sorting! i = 1:: 2, 9, 4, 7, 6, 2, 1, 5, i = 2:: 9, 2, 4, 7, 6, 2, 1, 5, i = 3:: 9, 4, 2, 7, 6, 2, 1, 5, i = 4:: 9, 7, 4, 2, 6, 2, 1, 5, i = 5:: 9, 7, 6, 4, 2, 2, 1, 5, i = 6:: 9, 7, 6, 4, 2, 2, 1, 5, i = 7:: 9, 7, 6, 4, 2, 2, 1, 5, Result = 9, 7, 6, 5, 4, 2, 2, 1, void InsertionSort (int A[ ], int size) { int i,j, item; for (i=1; i<size; i++) { printf("i = %d:: ",i); for (j=0;j<size;j++) printf("%d, ",A[j]); printf("\n"); item = A[i] ; for (j=i-1; j>=0; j--) if (item > A[j]) { A[j+1] = A[j]; A[j] = item ; } else break; } int main() { int X[100], i, size; scanf("%d",&size); for (i=0;i<size;i++) scanf("%d",&X[i]); InsertionSort(X,size); printf("Result = "); for (i=0;i<size;i++) printf("%d, ",X[i]); printf("\n"); return 0; }

33 Mergesort

34 Basic Idea Divide the array into two halves Sort the two sub-arrays Merge the two sorted sub-arrays into a single sorted array Step 2 (sorting the sub-arrays) is done recursively (divide in two, sort, merge) until the array has a single element (base condition of recursion)

35 Merging Two Sorted Arrays Problem : Two sorted arrays A and B are given. We are required to produce a final sorted array C which contains all elements of A and B.

37 Merge Code void merge (int A[], int B[], int C[], int m,int n) { int i=0,j=0,k=0; while (i<m && j<n) { if (A[i] < B[j]) C[k++] = A[i++]; else C[k++] = B[j++]; } while (i<m) C[k++] = A[i++]; while (j<n) C[k++] = B[j++]; }

38 Merge Sort: Sorting an array recursively void mergesort (int A[], int n) { int i, j, B[max]; if (n <= 1) return; i = n/2; mergesort(A, i); mergesort(A+i, n-i); merge(A, A+i, B, i, n-i); for (j=0; j<n; j++) A[j] = B[j]; free(B); }