Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Unit 4

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 62

UNIT – IV

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 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
2
• Could be very slow
Example: Successful Linear Search

3
Example: Failed Linear Search

5
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, location;

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; location = i;
} else
void read_array (double a[], int size) { location = -1;
int i;
printf("Enter %d integer numbers separated by return location;
blanks\n> ", size); }
for (i = 0; i < size; ++i)
scanf("%lf", &a[i]); 6
}
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
7
For Linear Search algorithm :O(n)
Binary Search
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)

• 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


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]); 10
}
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.

11
Bubble Sort Implementation
#include <stdio.h> void bubble_sort(double a[], int size) {
#define SIZE 10 int i,j, pass = 1, swap_occurs,temp;

void bubble_sort(double a[], int size); for(i=0;i<size;i++)


void read_array(double a[], int size); {
void print_array(double a[], int size); for(j=1;j<size-i;j++)
int main(void) { {
double x[SIZE]; if(a[j-1]>a[j])
{
int i;
temp=a[j-1];
a[j-1]=a[j];
read_array(x, SIZE); a[j]=temp;
printf("Before Sorting: "); }
print_array(x, SIZE); }
bubble_sort(x, SIZE); }
printf("After Sorting: "); }
print_array(x, SIZE); void read_array (double a[], int size) {
int i;
system("pause"); printf("Enter %d integer numbers separated by blanks\
n> ", size);
return 0;
for (i = 0; i < size; ++i)
}
scanf("%lf", &a[i]);
}
void print_array(double a[], int size) {
int i;

for (i = 0; i < size; ++i)


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

for (i = 0; i < size; ++i)


printf("%.1f ", a[i]); 45
printf("\n");
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; } 46
}
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.

47
Selection Sort Implementation
int find_min(double a[], int start, int size) {
#include <stdio.h>
#define SIZE 10 int i, min_index = start;

void selection_sort(double a[], int size); for (i=start+1; i<size; i++)


void read_array(double a[], int size); if (a[i] < a[min_index])
void print_array(double a[], int size); min_index = i;
int find_min(double a[], int start, int size);
void swap(double *a, double *b);
return min_index;
}
int main(void) {
double x[SIZE]; void swap(double *a, double *b) {
int i; double temp = *a;
*a = *b;
read_array(x, SIZE); *b = temp;
printf("Before Sorting: "); }
print_array(x, SIZE); void read_array (double a[], int size) {
selection_sort(x, SIZE);
int i;
printf("After Sorting: ");
printf("Enter %d integer numbers separated by blanks\
print_array(x, SIZE); n> ", size);
for (i = 0; i < size; ++i)
system("pause");
scanf("%lf", &a[i]);
return 0;
} }
void selection_sort(double a[], int size) { void print_array(double a[], int size) {
int i, min_pos; int i;

for (i = 0; i<size-1; i++) { for (i = 0; i < size; ++i)


min_pos = find_min(a, i, size); printf("%.1f ", a[i]);
swap(&a[i], &a[min_pos]); printf("\n");
} }
48
}
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.

49
#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
int min; elements:");
for(i = 1; i < n; i ++) scanf("%d",&n);
{ printf("\n Enter the elements :");
min = a[i]; for(i = 0; i < n; i++)
index = i; scanf("%d",&a[i]);
for(j = i; j > 0 ; j--) isort(a,n);
If(a[j-1] > min) printf("\n The elements in sorted
{ order is :\n");
a[j] = a[j -1]; for(i = 0; i < n; i++)
index = j-1; printf(" %d ",a[i]);
} getch();
a[index] = min; }
}
}

50
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

52
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
mid h
l
m
0 1 2 3 4 5 6 7
17 12 24 65 86 57 98 49
l m h
0 1 2 3 4 5 6 7
17 21 26 67 84 55 98 94

0
l,m 1 h 2 3 4 5 6 7
17 71 22 66 58 58 94 94

7 1 2 6 8 5 9 4
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");


for(i = 0; i < n; i++)
printf("%5d",a[i]);
getch();

}
55
void merge(int a[],int l,int h,int m)
#include "stdio.h" {
#include "conio.h" int c[100],i,j,k;
void merge(int [],int,int,int); i = l; j = m + 1; k = l;
void mergesort(int a[],int low,int high) while(i <= m && j <= h)
{ {
int mid; if(a[i] < a[j])
if(low < high) {
{ c[k] = a[i];
mid = (low + high)/2; i++; k++;
mergesort(a,low,mid); }
mergesort(a,mid+1,high); else
merge(a,low,high,mid); {
} 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];
}
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 57
Recursive implementation with the left most array entry selected as
the pivot element.

58
#include "studio"
#include "conio.h"

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");


for(i = 0; i < n; i++)
printf("%5d",a[i]);
getch();
}
59
int partition(int [], int,int);
void quicksort(int a[], int low, int high)
{
int i; int partition(int a[],int l,int r)
if (low<high) {
{ int p, i=l+1,j=r,temp;
i = partition(a,low,high); p = a[l];
quicksort(a,low,i-1); while(1)
quicksort(a,i+1,high); {
} while(a[i] <= p && i <= r)
} i++;
while(a[j] > p && j>=l)
j--;
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;
}
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 than61and
less than this pivot, and recursively sorts the partitions.
#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;
}
62

You might also like