Presentation is loading. Please wait.

Presentation is loading. Please wait.

UNIT – IV Searching – Linear search - binary search Sorting

Similar presentations


Presentation on theme: "UNIT – IV Searching – Linear search - binary search Sorting"— Presentation transcript:

1 UNIT – IV Searching – Linear search - binary search Sorting – Bubble sort - selection sort - Insertion sort - Quick sort - merge sort.

2 Searching and Sorting Linear Search
Searching is the process of finding a particular element in a list Sorting is the process of rearranging the elements in a list so that they are stored in some well-defined order Searching Algorithms Linear search: the search starts at the beginning of the list and goes straight down the line of elements until it finds a match or reaches the end of the list Binary search: the search starts at the center of a sorted list and determines which half to continue to search on that basis Linear Search The most basic Very easy to implement The list DOESN’T have to be sorted All list elements must be visited if the search fails Could be very slow

3 Example: Successful Linear Search

4

5 Example: Failed Linear Search

6 Linear Search Implementation
#include <stdio.h> #define SIZE 8 int linear_search(double a[], double target, int size); void read_array(double a[], int size); int main(void) { double x[SIZE], target; int index; read_array(x, SIZE); printf("Enter Element to search for: "); scanf("%lf", &target); index = linear_search(x, target, SIZE); if (index != -1) printf("Target was found at index %d\n", index); else printf("Sorry, target item was not found"); system("pause"); return 0; } void read_array (double a[], int size) { int i; printf("Enter %d integer numbers separated by blanks\n> ", size); for (i = 0; i < size; ++i) scanf("%lf", &a[i]); /* Searches for target in an array using Linear search; * Returns index of target or -1 if not found */ int linear_search(double a[], double target, int size) { int i, found = 0, location; i = 0; while (!found && i < size) { if (a[i] == target) found = 1; else ++i; } if (found) location = i; location = -1; return location;

7 Efficiency of Linear Search
Big O Notation Indicates the worst-case run time for an algorithm In other words, how hard an algorithm has to work to solve a problem Constant run time O(1) Does not grow as the size of the array increases Linear run time O(n) Grows proportional to the size of the array Logarithmic run time O(log n) Grows logarithmic proportional to the size of the array Quadratic run time O(n2) Grows proportional to the square of the size of the array For Linear Search algorithm :O(n)

8 Binary Search At each step it splits the remaining array elements into two groups Therefore, it is faster than the linear search Works only on an already SORTED array Thus, there is a performance penalty for sorting the array The algorithm starts searching with the middle element. If the item is less than the middle element, it starts over searching the first half of the list. If the item is greater than the middle element, the search starts over starting with the middle element in the second half of the list. It then continues halving the list until the item is found. Each iteration eliminates half of the remaining elements The Time complexity of Binary Search is O(log N)

9

10 Binary Search Implementation
#include <stdio.h> #define SIZE 8 int binary_search (double x[], int low, int high, double target); void read_array(double a[], int size); int main(void) { double x[SIZE], target; int index; read_array(x, SIZE); printf("Enter Element to search for: "); scanf("%lf", &target); index = binary_search(x, 0, SIZE-1, target); if (index != -1) printf("Target was found at index %d\n", index); else printf("Sorry, target item was not found"); system("pause"); return 0; } void read_array (double a[], int size) { int i; printf("Enter %d integer numbers separated by blanks\n> ", size); for (i = 0; i < size; ++i) scanf("%lf", &a[i]); /* Recursive implementation of binary search */ int binary_search (double x[], int low, int high, double target) { int middle; if (low > high) /*base case1:target not found*/ return -1; middle = (low + high)/2; if (x[middle] == target) return (middle); /*base case2:target found*/ else if (x[middle] < target) return binary_search(x, middle+1,high,target); else return binary_search(x, low, middle-1,target); }

11 Bubble Sort Algorithm The idea of Bubble (or exchange) sort is to scan through the list and swap each pair of adjacent elements that are in the wrong order. The process is repeated each time from index zero to one less than the previous limit until either the list is exhausted or until a pass that involve no swap is encountered. At the end of first pass, the largest element will move (or bubble up) to the end of the list. At the end of the second swap, the second largest will move to its right place, etc. The following table shows a trace of how bubble sort works.

12 Bubble Sort Implementation
#include <stdio.h> #define SIZE 10 void bubble_sort(double a[], int size); void read_array(double a[], int size); void print_array(double a[], int size); void swap(double *a, double *b); int main(void) { double x[SIZE]; int i; read_array(x, SIZE); printf("Before Sorting: "); print_array(x, SIZE); bubble_sort(x, SIZE); printf("After Sorting: "); system("pause"); return 0; } void swap(double *a, double *b) { double temp = *a; *a = *b; *b = temp; void bubble_sort(double a[], int size) { int i, pass = 1, swap_occurs; do{ swap_occurs = 0; for(i = 1; i <= size - pass; i++) { if (a[i - 1] > a[i]) { swap(&a[i-1], &a[i]); swap_occurs = 1; } pass++; } while (swap_occurs && pass <= size-1); void read_array (double a[], int size) { int i; printf("Enter %d integer numbers separated by blanks\n> ", size); for (i = 0; i < size; ++i) scanf("%lf", &a[i]); void print_array(double a[], int size) { for (i = 0; i < size; ++i) printf("%.1f ", a[i]); printf("\n");

13 Selection Sort Algorithm
Selection sort involved scanning through the list to find (or select) the smallest element and swap it with the first element. The rest of the list is then search for the next smallest and swap it with the second element. This process is repeated until the rest of the list reduces to one element, by which time the list is sorted. The following table shows how selection sort works.

14 Selection Sort Implementation
#include <stdio.h> #define SIZE 10 void selection_sort(double a[], int size); void read_array(double a[], int size); void print_array(double a[], int size); int find_min(double a[], int start, int size); void swap(double *a, double *b); int main(void) { double x[SIZE]; int i; read_array(x, SIZE); printf("Before Sorting: "); print_array(x, SIZE); selection_sort(x, SIZE); printf("After Sorting: "); system("pause"); return 0; } void selection_sort(double a[], int size) { int i, min_pos; for (i = 0; i<=size-2; i++) { min_pos = find_min(a, i, size); swap(&a[i], &a[min_pos]); int find_min(double a[], int start, int size) { int i, min_index = start; for (i=start+1; i<size; i++) if (a[i] < a[min_index]) min_index = i; return min_index; } void swap(double *a, double *b) { double temp = *a; *a = *b; *b = temp; void read_array (double a[], int size) { int i; printf("Enter %d integer numbers separated by blanks\n> ", size); for (i = 0; i < size; ++i) scanf("%lf", &a[i]); void print_array(double a[], int size) { for (i = 0; i < size; ++i) printf("%.1f ", a[i]); printf("\n");

15 Insertion Sort Strategy: Insertion of an element in proper order:
Begin with a sequence E of n elements in arbitrary order Initially assume the sorted segment contains first element Let x be the next element to be inserted in sorted segment, pull x “out of the way”, leaving a vacancy repeatedly compare x to the element just to the left of the vacancy, and as long as x is smaller, move that element into the vacancy, else put x in the vacancy, repeat the next element that has not yet examined.

16 #include "stdio.h" #include "conio.h" void isort(int a[],int n) { int i,j,index; int min; for(i = 1; i < n; i ++) min = a[i]; index = i; for(j = i; j > 0 ; j--) If(a[j-1] > min) a[j] = a[j -1]; index = j-1; } a[index] = min; void main() { int a[100],i,n; clrscr(); printf("\n Enter the no.of elements:"); scanf("%d",&n); printf("\n Enter the elements :"); for(i = 0; i < n; i++) scanf("%d",&a[i]); isort(a,n); printf("\n The elements in sorted order is :\n"); printf(" %d ",a[i]); getch(); }

17 Mergesort Split array A[0..n-1] into about equal halves and make copies of each half in arrays B and C Sort arrays B and C recursively Merge sorted arrays B and C into array A as follows: Repeat the following until no elements remain in one of the arrays: compare the first elements in the remaining unprocessed portions of the arrays copy the smaller of the two into A, while incrementing the index indicating the unprocessed portion of that array Once all elements in one of the arrays are processed, copy the remaining unprocessed elements from the other array into A.

18 Merge Sort

19

20 #include "stdio.h" #include "conio.h" void merge(int [],int,int,int); void mergesort(int a[],int low,int high){ int mid; if(low < high) { mid = (low + high)/2; mergesort(a,low,mid); mergesort(a,mid+1,high); merge(a,low,high,mid); } } void merge(int a[],int l,int h,int m){ int c[100],i,j,k; i = l; j = m + 1; k = l; while(i <= m && j <= h) { if(a[i] < a[j]){ c[k] = a[i]; i++; k++; } Else { c[k] = a[j]; j++; k++; } } while(i <= m) c[k++] = a[i++]; while(j <= h) c[k++] = a[j++]; for(i = l; i < k; i++) a[i] = c[i]; } void main() { int i,n,a[100]; clrscr(); printf("\n Enter the size of the array :"); scanf("%d",&n); printf("\n Enter the elements :\n"); for(i = 0; i < n; i++) scanf("%d",&a[i]); mergesort(a,0,n-1); printf("\n Elements in sorted order :\n"); printf("%5d",a[i]); getch(); }

21 Quicksort p A[i]≤p A[i]>p Select a pivot (partitioning element)
Rearrange the list so that all the elements in the positions before the pivot are smaller than or equal to the pivot and those after the pivot are larger than the pivot Exchange the pivot with the last element in the first (i.e., ≤) sublist – the pivot is now in its final position Sort the two sublists recursively p A[i]≤p A[i]>p

22 Recursive implementation with the left most array entry selected as the pivot element.

23 #include "stdio.h" #include "conio.h" int partition(int [],int,int); void quicksort(int a[],int low,int high) { int i; if(low<high) i = partition(a,low,high); quicksort(a,low,i-1); quicksort(a,i+1,high); } int partition(int a[],int l,int r) int val,i=l,j=r+1,temp; val = a[l]; while(1) do ++i;while(a[i] <= val && i <= r); do --j;while(a[j] > val); if(i >= j) break; temp = a[i]; a[i] = a[j]; a[j] = temp; temp = a[l]; a[l] = a[j]; a[j] = temp; return j; void main() { int i,n,a[100]; clrscr(); printf("\n Enter the size of the array :"); scanf("%d",&n); printf("\n Enter the elements :\n"); for(i = 0; i < n; i++) scanf("%d",&a[i]); quicksort(a,0,n-1); printf("\n The elements in sorted order is :\n"); printf("%5d",a[i]); getch(); }

24 Review of Algorithms Selection Sort An algorithm which orders items by repeatedly looking through remaining items to find the least one and moving it to a final location Bubble Sort Sort by comparing each adjacent pair of items in a list in turn, swapping the items if necessary, and repeating the pass through the list until no swaps are done Insertion Sort Sort by repeatedly taking the next item and inserting it into the final data structure in its proper order with respect to items already inserted. Merge Sort An algorithm which splits the items to be sorted into two groups, recursively sorts each group, and merges them into a final, sorted sequence Quick Sort An in-place sort algorithm that uses the divide and conquer paradigm. It picks an element from the array (the pivot), partitions the remaining elements into those greater than and less than this pivot, and recursively sorts the partitions.


Download ppt "UNIT – IV Searching – Linear search - binary search Sorting"

Similar presentations


Ads by Google