Unit 4
Unit 4
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
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;
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
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.