0% found this document useful (0 votes)
44 views23 pages

Unit 4

ppt4
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views23 pages

Unit 4

ppt4
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 23

UNIT – VI

Searching
– Linear search
- binary search

Sorting
– Bubble sort
- selection sort
- Insertion sort
- Quick sort
- merge sort.

1
Searching and Sorting
• Searching is the process of finding a particular element in an array
• Sorting is the process of rearranging the elements in an array so
that they are stored in some well-defined order
Searching Algorithms
• Linear search: the search starts at the beginning of the array and
goes straight down the line of elements until it finds a match or
reaches the end of the array
• Binary search: the search starts at the center of a sorted array and
determines which half to continue to search on that basis

Linear Search
• The most basic
• Very easy to implement
• The array DOESN’T have to be sorted
• All array elements must be visited if the search fails
• 2
Could be very slow
Example: Successful Linear Search

3
Example: Failed Linear Search

4
Linear Search Implementation
#include <stdio.h> /* Searches for target in an array using Linear
#define SIZE 8 search;
int linear_search(double a[], double target, int size); * Returns index of target or -1 if not found */
void read_array(double a[], int size);
int linear_search(double a[], double target,
int main(void) { int size)
double x[SIZE], target; {
int index; int i, found = 0, where;

read_array(x, SIZE); i = 0;
printf("Enter Element to search for: "); while (!found && i < size) {
scanf("%lf", &target); if (a[i] == target)
index = linear_search(x, target, SIZE); found = 1;
if (index != -1) else
printf("Target was found at index %d\n", index); ++i;
else }
printf("Sorry, target item was not found");
system("pause"); if (found)
return 0; where = i;
} else
void read_array (double a[], int size) { where = -1;
int i;
printf("Enter %d integer numbers separated by return where;
blanks\n> ", size); }
for (i = 0; i < size; ++i)
scanf("%lf", &a[i]); 5
}
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
6
For Linear Search algorithm :O(n)
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
7
• The Time complexity of Binary Search is O(log N)
8
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); /* Recursive implementation of binary search */
int binary_search (double x[], int low, int high,
int main(void) { double target) {
double x[SIZE], target; int middle;
int index;
if (low > high) /*base case1:target not found*/
read_array(x, SIZE); return -1;
printf("Enter Element to search for: ");
scanf("%lf", &target); middle = (low + high)/2;
index = binary_search(x, 0, SIZE-1, target); if (x[middle] == target)
if (index != -1) return (middle); /*base case2:target
printf("Target was found at index %d\n", index); found*/
else else if (x[middle] < target)
printf("Sorry, target item was not found"); return binary_search(x,
system("pause"); middle+1,high,target);
return 0; else
} return binary_search(x, low,
void read_array (double a[], int size) { middle-1,target);
int i; }
printf("Enter %d integer numbers separated by blanks\n>
", size);
for (i = 0; i < size; ++i)
scanf("%lf", &a[i]); 9
}
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.

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

12
Selection Sort Implementation
#include <stdio.h>
#define SIZE 10 int find_min(double a[], int start, int size) {
int i, min_index = start;
void selection_sort(double a[], int size);
void read_array(double a[], int size);
for (i=start+1; i<size; i++)
void print_array(double a[], int size);
if (a[i] < a[min_index])
int find_min(double a[], int start, int size);
void swap(double *a, double *b); min_index = i;

int main(void) { return min_index;


double x[SIZE]; }
int i; void swap(double *a, double *b) {
double temp = *a;
read_array(x, SIZE);
*a = *b;
printf("Before Sorting: ");
*b = temp;
print_array(x, SIZE);
selection_sort(x, SIZE); }
printf("After Sorting: "); void read_array (double a[], int size) {
print_array(x, SIZE); int i;
printf("Enter %d integer numbers separated by blanks\
system("pause"); n> ", size);
return 0; for (i = 0; i < size; ++i)
} scanf("%lf", &a[i]);
void selection_sort(double a[], int size) { }
int i, min_pos; void print_array(double a[], int size) {
int i;
for (i = 0; i<=size-2; i++) {
min_pos = find_min(a, i, size); for (i = 0; i < size; ++i)
swap(&a[i], &a[min_pos]); printf("%.1f ", a[i]);
} printf("\n");
} 13
}
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.

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

15
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.
Merge Sort

17
8 3 2 9 7 1 5 4

8 3 2 9 7 1 5 4

8 3 2 9 7 1 5 4

8 3 2 9 7 1 5 4

3 8 2 9 1 7 4 5

2 3 8 9 1 4 5 7

1 2 3 4 5 7 8 9
#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) { void main()
mid = (low + high)/2; {
mergesort(a,low,mid); int i,n,a[100];
mergesort(a,mid+1,high); clrscr();
merge(a,low,high,mid); } } printf("\n Enter the size of the array :");
void merge(int a[],int l,int h,int m){ scanf("%d",&n);
int c[100],i,j,k; printf("\n Enter the elements :\n");
i = l; j = m + 1; k = l; for(i = 0; i < n; i++)
while(i <= m && j <= h) { scanf("%d",&a[i]);
if(a[i] < a[j]){ mergesort(a,0,n-1);
c[k] = a[i]; i++; k++; } printf("\n Elements in sorted order :\n");
Else { c[k] = a[j]; j++; k++; } } for(i = 0; i < n; i++)
while(i <= m) c[k++] = a[i++]; printf("%5d",a[i]);
while(j <= h) c[k++] = a[j++]; getch();
for(i = l; i < k; i++) a[i] = c[i]; } 19
}
Quicksort

 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

A[i]≤p A[i]>p 20
Recursive implementation with the left most array entry selected as
the pivot element.

21
#include "stdio.h"
#include "conio.h"
void main()
int partition(int [],int,int);
{
void quicksort(int a[],int low,int high)
int i,n,a[100];
{
clrscr();
int i;
printf("\n Enter the size of the array :");
if(low<high)
scanf("%d",&n);
{
printf("\n Enter the elements :\n");
i = partition(a,low,high);
for(i = 0; i < n; i++)
quicksort(a,low,i-1);
scanf("%d",&a[i]);
quicksort(a,i+1,high);
quicksort(a,0,n-1);
printf("\n The elements in sorted order is :\n");
}
for(i = 0; i < n; i++)
}
printf("%5d",a[i]);
int partition(int a[],int l,int r)
getch();
{
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;
}
22
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 than23and
less than this pivot, and recursively sorts the partitions.

You might also like