unit iv(dsc++)

98
Unit-IV Unit-IV 1.Searching techniques 1.Searching techniques linear search method linear search method binary search method binary search method . . Hashing Hashing Hash table representation Hash table representation Hash functions Hash functions Collision resolution techniques Collision resolution techniques Chaining, linear probing, Chaining, linear probing, quadratic probing, double hashing quadratic probing, double hashing . . Sorting techniques Sorting techniques bubble sort bubble sort selection sort. selection sort. insertion sort. insertion sort. quick sort quick sort merge sort merge sort . . Sathi Durga Devi, Dept of IT

Upload: durga-devi

Post on 13-Apr-2017

103 views

Category:

Engineering


1 download

TRANSCRIPT

Page 1: Unit iv(dsc++)

Unit-IVUnit-IV1.Searching techniques1.Searching techniques linear search methodlinear search method

binary search methodbinary search method..HashingHashing Hash table representationHash table representation Hash functionsHash functionsCollision resolution techniquesCollision resolution techniques

Chaining, linear probing, Chaining, linear probing, quadratic probing, double hashingquadratic probing, double hashing..

Sorting techniquesSorting techniquesbubble sortbubble sort

selection sort.selection sort. insertion sort.insertion sort. quick sortquick sort merge sortmerge sort..Sathi Durga Devi, Dept of IT

Page 2: Unit iv(dsc++)

Searching and SortingSearching 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 AlgorithmsSearching 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

Sathi Durga Devi, Dept of IT

Page 3: Unit iv(dsc++)

Linear\sequential Search

• linear\sequential search of a list/array begins at the beginning of the list/array and continues until the item is found or the entire list/array has been searched

Sathi Durga Devi, Dept of IT

Page 4: Unit iv(dsc++)

Example: Successful Linear Search

Sathi Durga Devi, Dept of IT

Page 5: Unit iv(dsc++)

Example: Failed Linear Search

Sathi Durga Devi, Dept of IT

Page 6: Unit iv(dsc++)

Linear Search Implementation using non recursive method#include <stdio.h>#define SIZE 8int linear_search(int a[], int target, int size);void read_array(int a[], int size);int main(void) { int x[SIZE], target; int index;

read_array(x, SIZE); printf("Enter Element to search for: "); scanf("%d", &target); index = linear_search(x, target, SIZE); if (index != 0) printf("Target was found at index %d\

n", index); else printf("Sorry, target item was not

found");

return 0;

}void read_array (int a[], int size) { int i; printf("Enter %d integer numbers

separated by blanks\n> ", size); for (i = 0; i < size; ++i) scanf("%d", &a[i]);}

/* Searches for an target in an array using Linear search; * Returns index of target or -1 if not found */

int linear_search(int a[], int target, int size){ int i,loc=0; for(i=0;i<SIZE;i++) { if(target==a[i]) return ++loc; else loc++; } return 0;}

Sathi Durga Devi, Dept of IT

Page 7: Unit iv(dsc++)

/* C program that use recursive function to perform the Linear Search for a Key value in a given list of integers*/

#include<stdio.h> #define SIZE 5int linearSearch(int array[], int index, int length, int value);void main() {int list[SIZE],element,i,target,index=0;printf("\n\nEnter %d integer elements: ",SIZE);for(i = 0; i < SIZE; i++) {

scanf("%d",&list[i]);}printf("\nEnter target element to be searched: ");scanf("%d",&target);element = linearSearch( list,index,SIZE,target);if( element != -1 )

printf("\nElement is found at %d location ",element+1);else

printf("Element is not found...");}

Sathi Durga Devi, Dept of IT

Page 8: Unit iv(dsc++)

int linearSearch(int array[], int index,int length, int value){

if(index>length-1)return -1;

elseif (array[index]==value)

return index;else

return linearSearch( array,index+1,length, value);}

Sathi Durga Devi, Dept of IT

Page 9: Unit iv(dsc++)

Search Algorithms

-All the array elements must be visited if search fails.Sathi Durga Devi, Dept of IT

Page 10: Unit iv(dsc++)

Efficiency of Linear Search • The efficiency of an algorithm is measured using the big O notation

( O stands for order of )• Big O Notation

– Indicates the worst-case run time (maximum time taken for execution) for an algorithm

– In other words, how hard an algorithm has to work to solve a problem

For Linear Search algorithm :O(n)

Sathi Durga Devi, Dept of IT

Page 11: Unit iv(dsc++)

Binary Search: The search starts at middle of a sorted array, if middle is equal to target element search is successful otherwise it determines which half to be continue to search on that basis. The algorithm starts searching with the mid element.

mid=(first + last)/2 If the item is equal to mid then search is successful. If the item is less than the mid element, it starts over

searching the first half of the list. If the item is greater than the mid element, the search

starts over 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.

It is faster than the linear search. It works only on SORTED array. Thus, there is a performance penalty for sorting the array. The Time complexity of Binary Search is O(log N).

Sathi Durga Devi, Dept of IT

Page 12: Unit iv(dsc++)

Sathi Durga Devi, Dept of IT

Page 13: Unit iv(dsc++)

/* C program that use recursive function to perform the Binary Search for a Key value in a given list of integers*/

#include <stdio.h> #define SIZE 8int binary_search (int list[], int low, int high, int target);

void main() {int list[SIZE], target, index,i;

printf("Enter %d elements in ascending or descending order: ",SIZE);for(i=0;i<SIZE;i++)

scanf("%d",&list[i]);printf("Enter an element that is to be searched: ");scanf("%d", &target);index = binary_search(list, 0, SIZE-1, target);if (index != -1)

printf("\nTarget was found at index: %d ", index+1);else

printf("Sorry, target item was not found");}

Sathi Durga Devi, Dept of IT

Page 14: Unit iv(dsc++)

int binary_search (int list[], int low, int high, int target) {

int middle;if (low > high)

return -1;middle = (low + high)/2;if (list[middle] == target)

return (middle);elseif (list[middle] < target)

return binary_search(list,middle+1,high,target);else

return binary_search(list,low,middle-1,target);}

Sathi Durga Devi, Dept of IT

Page 15: Unit iv(dsc++)

/* C program that use non recursive function to perform the Binary Search for a Key value in a given list of integers*/#include <stdio.h>#define SIZE 8int binary_search (int list[], int low, int high, int target);void main() {

int list[SIZE], target, index,i;printf(“\nenter the array elements”);for(i=0;i<SIZE;i++)

scanf("%d",&list[i]);printf(“\n enter the target element");scanf("%d", &target);index = binary_search(list, 0, SIZE-1, target);if (index != -1)

printf("\nelement atlocation %d ", index+1);else

printf("Sorry, target item was not found");getch();

} Sathi Durga Devi, Dept of IT

Page 16: Unit iv(dsc++)

int binary_search(int a[],int low, int high, int target){int middle;while(low<=high){ middle=(low+high)/2; if(target<a[middle]) high=middle-1; else if(target>a[middle]) low=middle+1; else return middle; }//whilereturn -1;}//binary_search()

Sathi Durga Devi, Dept of IT

Page 17: Unit iv(dsc++)

Hashing

Sathi Durga Devi, Dept of IT

Page 18: Unit iv(dsc++)

Why hashing?• Internet has grown to millions of users and terabytes of

data every data.• It is impossible to find anything in the internet, unless we

develop a new data structure to store and access the data very quickly.

• The amount of time required to look up an element in an array or linked list is either O(logn) or O(n) based on the list is sorted or not.

• New data structure called Hashing used to store and retrieve any entry with constant time O(1).

• This technique is irrelevant to size of the list and order.• To increase the search efficiency the items to be stored in

such a way as to make it easy to find them later.

Sathi Durga Devi, Dept of IT

Page 19: Unit iv(dsc++)

Hashing- Hashing is a technique used to generate key where an element is

to be inserted or to be located from.

• Hash Table - hash table is a data structure to store and retrieve data very

fast. - hash table consist of key and its value. - Each location in the hash table is called cell or bucket. - hash table is implemented using array. - An element is accessed very fast if we know the key or its index.Example- to store the Student record in hash table, Student rollno is

used as a key

Sathi Durga Devi, Dept of IT

Page 20: Unit iv(dsc++)

Hash Function - to map the key value into its corresponding index in hash table

hash function is used.A hash function h transforms a key into an index in a hash table

T[0…m-1]:Where m is size of hash table.

-Use hash function to compute the index in the hash table for the given key value.-Hash function returns integer value which give the index value in the hash table.

Sathi Durga Devi, Dept of IT

Page 21: Unit iv(dsc++)

Types of hash functions1. Division method2. Mid square3. Digit folding

Sathi Durga Devi, Dept of IT

Page 22: Unit iv(dsc++)

1. Division method h(key)= record%M where M is size of the hash tableExample: store following records in hash table 34, 20, 67, 8, 23. M is 10 use hash function to map them in hash table

0 20123 234 34567 678 89

34%10= 420%10=067%10=78%10=823%10=3

Sathi Durga Devi, Dept of IT

Page 23: Unit iv(dsc++)

Consider the following elements to be placed in the hash table of size 10,

37,90,45,22,17,49,55

37

45

90

22H1(37)=37%10=7H1(90)=90%10=0H1(45)=45%10=5H1(22)=22%10=2H1(17)=17%10=7H1(49)=49%10=9H1(55)=55%10=5

In above example 17 and 55 are hashed to same location this condition is called collision

Sathi Durga Devi, Dept of IT

Page 24: Unit iv(dsc++)

2. Mid square- Square the key value and the middle or mid part of the

result is used as index.- Example to place a record 3111 then- Square of 3111= 9678321- If the hash table size is 1000 then consider the middle 3

digits 783.

Sathi Durga Devi, Dept of IT

K 3205 7148k2 10272025 51093904H(k) 72 93

Page 25: Unit iv(dsc++)

3. Folding method - Key value is divided into parts and add

them yields required hash address.

Sathi Durga Devi, Dept of IT

Key 3205 7148H(key) 32+05=37 71+48=19

Note- the leading digit 1 in H(7148) is ignored.

Page 26: Unit iv(dsc++)

Collision resolution techniques• Two or more keys are mapping to same location in the

hash table is called collision.Collision resolution techniques• They are two broad ways of collision resolution techniques1. Separate chaining: an array of linked list representation

2. Open addressing: array based implementation (i) Linear probing (linear search)

(ii) Quadratic probing (nonlinear search) (iii) Double hashing (uses two hash functions

Sathi Durga Devi, Dept of IT

Page 27: Unit iv(dsc++)

Separate chaining• Hash table is implemented as array of linked list.• All the records which are mapped to same hash address are lined together to form a linked list.• Example: Load the keys 23, 13, 21, 14, 7, 8, and 15 , in this order, in a hash table of size 7 using separate chaining with the hash function: h(key) = key % 7

h(23) = 23 % 7 = 2 h(13) = 13 % 7 = 6

h(21) = 21 % 7 = 0h(14) = 14 % 7 = 0 collisionh(7) = 7 % 7 = 0 collisionh(8) = 8 % 7 = 1 h(15) = 15 % 7 = 1 collision

Sathi Durga Devi, Dept of IT

Page 28: Unit iv(dsc++)

Linear probing (linear search)• Idea is that when the collision occurs, find the next

available slot in the hash table (i.e probing)• The process wraps around to the beginning of the table• Example 89, 18, 49, 58, 9 and hash table size is 10

0 1 2 3 4 5 6 7 8 9

891849 58 9

89%10=918%10=849%10=958%10=89%10=9 Sathi Durga Devi, Dept of IT

Page 29: Unit iv(dsc++)

3. Quadratic probing- It operates by taking hash value and adding successive

values of an arbitrary quadratic polynomial.- Uses following formula

Sathi Durga Devi, Dept of IT

Hi(key)= (Hashvalue+i2)%mWhere, m may be table size or any prime number

Page 30: Unit iv(dsc++)

Ex- 37,99,55,22,11, 17,40,87

Sathi Durga Devi, Dept of IT

0 1 2 3 4 5 6 7 8 9

37%10=7

37

99%10=9

99

55%10=5

55

22%10=2

22

11%10=1

11

17%10=7 but already occupiedConsider i=0 then(17+02)%10=7(17+12)%10=8

17

40%10=0

40

87%10=7 occupied(87+12)%10=8 occupied(87+22)%10=1 occupied(87+32)%10=6

87

Page 31: Unit iv(dsc++)

4. Double hashing- Second hash function is applied when a collision is occurred.- the resultant of second hash function is to get the number of

positions from the point of collision to insert.

Sathi Durga Devi, Dept of IT

H1(key)= keyvalue%tablesizeH2(key)= M-(key % M)Where,M is prime number smaller than table size.

Page 32: Unit iv(dsc++)

Ex- 37,90,45,22,17,49,55

Sathi Durga Devi, Dept of IT

0 1 2 3 4 5 6 7 8 9

H1(37)=37%10=7

37

H1(90)=90%10=0

90

H1(45)=45%10=5

45

H1(22)=22%10=2

17

H1(17)=17%10=7H2(17)=7-(17%7)=4Move 4 locations from collision

H1(55)=55%10=5H2(55)=7-(55%7)=1Move one location from collision

H1(49)=49%10=9

495522

Page 33: Unit iv(dsc++)

Sorting Techniques1. Bubble sort/exchange sort2. Insertion sort3. Selection sort4. Merge sort5. Quick sort

Sathi Durga Devi, Dept of IT

Page 34: Unit iv(dsc++)

Bubble Sort

Sathi Durga Devi, Dept of IT

Page 35: Unit iv(dsc++)

Bubble sort\exchange sort• Suppose the list of numbers a[1],a[2],…,a[n] is in

memory. The bubble sort algorithm works as follows.Step 1- compare a[1] and a[2] and arrange them in the

desired order, so that a[1]<a[2]. then compare a[2] and a[3] and arrange them so that

a[2]<a[3]. Then compare a[3] and a[4] and arrange them so that a[3]< a[4]. Continue until we compare a[n-1] with a[n] and arrange them so that a[n-1]<a[n].

- Observe that step-1 involves n-1 comparisons. when step-1 is completed a[n] has the largest element in the list. The largest element is “bubbled up “ to the nth position.

Step 2- repeat step1 with one less comparision; it involves n-2 comparisions and when step2 is completed the second largest element will occupy a[n-1].

Step 3- repeat step1 with two fewer comparisons; involves n-3 comparisons.

Step n-1. compare a[1] with a[2] and arrange them so that a[1]<a[2].

After n-1 steps, the list will be sorted in increasing order.The process of sequentially traversing through all or part of

the list is frequently called a “pass”Sathi Durga Devi, Dept of IT

Page 36: Unit iv(dsc++)

Bubble sort27 32 51 23 13

51 23 13Pass-1

27 23 13

27

3232

51

27 32 1351

23

27 32 23 51

13

Sathi Durga Devi, Dept of IT

Page 37: Unit iv(dsc++)

Bubble sort

Pass-2 23 13 5127

32

27 13 5132

23

27 23 32

13 51

27 23 13 5132

Sathi Durga Devi, Dept of IT

Page 38: Unit iv(dsc++)

27 23 13 5132Pass-3

13 513227

23

23 513227

13

23 13 513227

Pass-4 51322723

13

Sorted Array after N-1 passes

13 23 27 32 51

Sathi Durga Devi, Dept of IT

Page 39: Unit iv(dsc++)

/* Write a c program to implement the bubble sort */#include<stdio.h>

void bubbleSort(int a[],int index,int size);void main() {

int n,a[10],i;printf("\n\nEnter the size of array: ");scanf("%d",&n);printf("\n\nEnter the elements: ");for(i=0;i<n;i++)

scanf("%d",&a[i]);printf("\n\nElements before sorting: ");for(i=0;i<n;i++)

printf(" %d",a[i]);printf("\n");bubbleSort(a,0,n);}

Sathi Durga Devi, Dept of IT

Page 40: Unit iv(dsc++)

void bubblesort(int a[],int index, int n){int i,x,j,temp;for(i=1;i<=n-1;i++){ printf("\n pass- %d \n",i); for(j=index;j<n-i;j++) { if(a[j]>a[j+1]) { temp=a[j]; a[j]=a[j+1]; a[j+1]=temp; }//iffor(x=0;x<n;x++) printf("%3d",a[x]); printf("\n\n"); }//j}//iprintf("\n elements after sorting\n");for(i=0;i<n;i++)printf("%3d",a[i]);}//bublesort

Time complexity- O(n2)

Sathi Durga Devi, Dept of IT

Page 41: Unit iv(dsc++)

41

Selection SortProcedure: Selection sort involved scanning through the list to 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.

Sathi Durga Devi, Dept of IT

Page 42: Unit iv(dsc++)

Pass-1

Pass-2

Pass-3

Pass-4

Pass-5

Pass-6

Pass-7

11

22

66

88

55

44

33

77

11

22

66

88

55

44

33

77

77

22

66

88

55

44

33

11

77

33

66

88

55

44

22

11

77

44

66

88

55

33

22

11

77

55

66

88

44

33

22

11

77

88

66

55

44

33

22

11

77

88

66

55

44

33

22

11

Sathi Durga Devi, Dept of IT

Page 43: Unit iv(dsc++)

Write a C program to implement Selection sort

#include<stdio.h>void selectionsort(int a[],int n);void main(){int a[100],i,n;printf("\n enter the size of the array");scanf("%d",&n);printf("enter array elements");for(i=0;i<n;i++)scanf("%d",&a[i]);selectionsort(a,n);}//main

Sathi Durga Devi, Dept of IT

Page 44: Unit iv(dsc++)

void selectionsort(int a[],int n){int i,j,k,loc,min,temp;for(i=0;i<n-1;i++){printf("\n");printf("\nstep-%d",i+1);min=a[i];loc=i;

for(j=i+1;j<=n-1;j++){ if(min>a[j]) { min=a[j]; loc=j;}}//jtemp=a[i];a[i]=a[loc];a[loc]=temp;for(k=0;k<n;k++)printf("%3d",a[k]);}//iprintf("\n\n sorted array is ");for(k=0;k<n;k++)printf("%3d",a[k]);}//selectionsort

Sathi Durga Devi, Dept of IT

Page 45: Unit iv(dsc++)

Insertion Sort• Idea: like sorting a hand of playing cards

– Start with an empty left hand and the cards facing down on the table.

– Remove one card at a time from the table, and insert it into the correct position in the left hand

• compare it with each of the cards already in the hand, from right to left

– The cards held in the left hand are sortedthese cards were originally the top cards of the pile

on the table

Sathi Durga Devi, Dept of IT

Page 46: Unit iv(dsc++)

Insertion Sort

To insert 12, we need to make room for it by moving first 36 and then 24.

6 10 24

12

36

Sathi Durga Devi, Dept of IT

Page 47: Unit iv(dsc++)

Insertion Sort

6 10 24 36

12

Sathi Durga Devi, Dept of IT

Page 48: Unit iv(dsc++)

Insertion Sort

6 10 24 36

12

Sathi Durga Devi, Dept of IT

Page 49: Unit iv(dsc++)

49

Insertion SortUsing insertion sort an element is inserted in correct location.Insertion sort scans the list from A[0] to A[n-1], insert each element A[k] into its

proper position in previously sorted sub list A[0],A[1],A[2]…A[k-1]..Procedure: A[0] by itself is trivially sorted. A[1] is inserted either before or after A[0] so that A[0],A[1] is sorted. A[2] is inserted into its proper place in A[0],A[1], that is, before A[0],

between A[0] and A[1], or after A[1] so that A[0],A[1],A[2] is sorted. Repeatedly compare A[k] to the element just to the left of the vacancy, and

as long as A[k] is smaller, move that element into the vacancy, else put A[k] in the vacancy.

Repeat the next element that has not yet examined. Time complexity- O(n2) This algorithm is used when n is small.

Sathi Durga Devi, Dept of IT

Page 50: Unit iv(dsc++)

50

Insertion Sort

Sathi Durga Devi, Dept of IT

Page 51: Unit iv(dsc++)

Insertion Sort5 2 4 6 1 3

input array

left sub-array right sub-array

at each iteration, the array is divided in two sub-arrays:

sorted unsorted

Sathi Durga Devi, Dept of IT

Page 52: Unit iv(dsc++)

Insertion Sort

Sathi Durga Devi, Dept of IT

Page 53: Unit iv(dsc++)

/*Write a program to implement the insertion sort*/#include<stdio.h>void insertsort(int a[],int n);void main(){int i,a[10],n;printf("\n enter array size");scanf("%d",&n);printf("\n enter array elements");for(i=0;i<n;i++)scanf("%d",&a[i]);printf("\n elements before swapping");for(i=0;i<n;i++)printf("%3d",a[i]);insertsort(a,n);printf("\n elements after swapping");for(i=0;i<n;i++)printf("%3d",a[i]);}//main

Sathi Durga Devi, Dept of IT

Page 54: Unit iv(dsc++)

void insertsort(int a[],int n){int k,temp,j,i;//stepsfor(k=0;k<n;k++){ printf("\nstep-%d",k+1); temp=a[k]; j=k-1; while((j>=0)&&(temp<=a[j])) { a[j+1]=a[j]; a[j]=temp; j--; }//while for(i=0;i<n;i++) printf("%3d",a[i]); }//for}//insertsort

Sathi Durga Devi, Dept of IT

Page 55: Unit iv(dsc++)

Merge Sort This algorithm uses the divide- and – conquer method. 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.

Sathi Durga Devi, Dept of IT

Page 56: Unit iv(dsc++)

Merge Sort

Sathi Durga Devi, Dept of IT

Page 57: Unit iv(dsc++)

mergesort(a,0,7)

mergesort(a,0,3) mergesort(a,4,7)

mergesort(a,0,1) mergesort(a,2,3) mergesort(a,4,5) mergesort(a,6,7)8 3 2 9 7 1 5 4

mergsort(a,0,0)ms(a,1,1) ms(a,2,2) ms(a,3,3) ms(a,4,4) ms(a,5,5) ms(a,6,6) ms(a,7,7)

8 3 2 9 7 1 5 4

8 3 2 9 7 1 5 4

8 3 2 9 7 1 5 4

merge(a,0,1,0) merge(a,2,3,2) merge(a,4,5,4) merge(a,6,7,6)3 8 2 9 1 7 4 5

merge(a,0,3,1) merge(a,4,7,5)2 3 8 9 1 4 5 7

merge(a,0,7,3)1 2 3 4 5 7 8 9

Sathi Durga Devi, Dept of IT

Page 58: Unit iv(dsc++)

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 9Sathi Durga Devi, Dept of IT

Page 59: Unit iv(dsc++)

#include "stdio.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);

} //if}//mergesort

Mergsort program

Sathi Durga Devi, Dept of IT

Page 60: Unit iv(dsc++)

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++; }//ifelse { c[k] = a[j]; j++; k++; } //else}//while while(i <= m) c[k++] = a[i++]; while(j <= h) c[k++] = a[j++]; for(i = l; i < k; i++) a[i] = c[i]; }//merge

Sathi Durga Devi, Dept of IT

Page 61: Unit iv(dsc++)

void main(){

int i,n,a[100];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();

}

Sathi Durga Devi, Dept of IT

Page 62: Unit iv(dsc++)

This algorithm uses the divide- and – conquer method. Select a pivot element from the array of elements. Rearrange the list so that all the elements before the pivot are smaller

than or equal to the pivot and those after the pivot are larger than the pivot .

After such a partitioning, the pivot is placed in its final position. Sort the two sublists recursively.

Quick Sort

Sathi Durga Devi, Dept of IT

Page 63: Unit iv(dsc++)

Quicksort AlgorithmGiven an array of n elements (e.g., integers):• If array only contains one element, return• Else

– pick one element to use as pivot.– Partition elements into two sub-arrays:

• Elements less than or equal to pivot• Elements greater than pivot

– Quicksort two sub-arrays– Return results

Sathi Durga Devi, Dept of IT

Page 64: Unit iv(dsc++)

Sathi Durga Devi, Dept of IT

Page 65: Unit iv(dsc++)

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

Sathi Durga Devi, Dept of IT

Page 66: Unit iv(dsc++)

/*Write a c program to implement the quick sort*/

#include<stdio.h>void quicksort(int [10],int,int);

int main(){int x[20],size,i;printf("\nEnter size of the array: ");scanf("%d",&size);printf("\nEnter %d elements: ",size);for(i=0;i<size;i++)

scanf("%d",&x[i]);quicksort(x,0,size-1);printf("\nSorted elements: ");for(i=0;i<size;i++)

printf(" %d",x[i]);getch();return 0;

}Sathi Durga Devi, Dept of IT

Page 67: Unit iv(dsc++)

void quicksort(int x[10],int first,int last){int pivot,j,temp,i;if(first<last){

pivot=first;i=first;

j=last;while(i<j){

while(x[i]<=x[pivot]&&i<last)i++;

while(x[j]>x[pivot])j--;

if(i<j){temp=x[i];

x[i]=x[j]; x[j]=temp;}

}temp=x[pivot];x[pivot]=x[j];x[j]=temp;quicksort(x,first,j-1);quicksort(x,j+1,last);

}} Sathi Durga Devi, Dept of IT

Page 68: Unit iv(dsc++)

40 20 10 80 60 50 7 30 100pivot_index = 0

i j

[0] [1] [2] [3] [4] [5] [6] [7] [8]

Sathi Durga Devi, Dept of IT

Page 69: Unit iv(dsc++)

40 20 10 80 60 50 7 30 100pivot_index = 0

i j

1. While x[i] <= x[pivot]++i

[0] [1] [2] [3] [4] [5] [6] [7] [8]

Sathi Durga Devi, Dept of IT

Page 70: Unit iv(dsc++)

40 20 10 80 60 50 7 30 100pivot_index = 0

i j

1. While x[i] <= x[pivot]++i

[0] [1] [2] [3] [4] [5] [6] [7] [8]

Sathi Durga Devi, Dept of IT

Page 71: Unit iv(dsc++)

40 20 10 80 60 50 7 30 100pivot_index = 0

i j

1. Whilex[i] <= x[pivot]++i

[0] [1] [2] [3] [4] [5] [6] [7] [8]

Sathi Durga Devi, Dept of IT

Page 72: Unit iv(dsc++)

40 20 10 80 60 50 7 30 100pivot_index = 0

i j

1. While x[i] <= x[pivot]++i

2. While x[j] > x[pivot]--j

[0] [1] [2] [3] [4] [5] [6] [7] [8]

Sathi Durga Devi, Dept of IT

Page 73: Unit iv(dsc++)

40 20 10 80 60 50 7 30 100pivot_index = 0

i j

1. While x[i] <= x[pivot]++i

2. While x[j] > x[pivot]--j

[0] [1] [2] [3] [4] [5] [6] [7] [8]

Sathi Durga Devi, Dept of IT

Page 74: Unit iv(dsc++)

40 20 10 80 60 50 7 30 100pivot_index = 0

i j

1. While x[i] <= x[pivot]++i

2. While x[j] > x[pivot]--j

3. If i < jswap x[i] and x[j]

[0] [1] [2] [3] [4] [5] [6] [7] [8]

Sathi Durga Devi, Dept of IT

Page 75: Unit iv(dsc++)

40 20 10 30 60 50 7 80 100pivot_index = 0

i j

1. While x[i] <= x[pivot]++i

2. While x[j] > x[pivot]--j

3. If i < jswap x[i] and x[j]

[0] [1] [2] [3] [4] [5] [6] [7] [8]

Sathi Durga Devi, Dept of IT

Page 76: Unit iv(dsc++)

40 20 10 30 60 50 7 80 100pivot_index = 0

i j

1. While x[i] <= x[pivot]++i

2. While x[j] > x[pivot]--j

3. If i < jswap x[i] and x[j]

4. While j > i, go to 1.

[0] [1] [2] [3] [4] [5] [6] [7] [8]

Sathi Durga Devi, Dept of IT

Page 77: Unit iv(dsc++)

40 20 10 30 60 50 7 80 100pivot_index = 0

i j

1. While x[i] <= x[pivot]++i

2. While x[j] > x[pivot]--j

3. If i < jswap x[i] and x[j]

4. While j > i, go to 1.

[0] [1] [2] [3] [4] [5] [6] [7] [8]

Sathi Durga Devi, Dept of IT

Page 78: Unit iv(dsc++)

40 20 10 30 60 50 7 80 100pivot_index = 0

i j

1. While x[i] <= x[pivot]++i

2. While x[j] > x[pivot]--j

3. If i < jswap x[i] and x[j]

4. While j > i, go to 1.

[0] [1] [2] [3] [4] [5] [6] [7] [8]

Sathi Durga Devi, Dept of IT

Page 79: Unit iv(dsc++)

40 20 10 30 60 50 7 80 100pivot_index = 0

i j

1. While x[i] <= x[pivot]++i

2. While x[j] > x[pivot]--j

3. If i < jswap x[i] and x[j]

4. While j > i, go to 1.

[0] [1] [2] [3] [4] [5] [6] [7] [8]

Sathi Durga Devi, Dept of IT

Page 80: Unit iv(dsc++)

40 20 10 30 60 50 7 80 100pivot_index = 0

i j

1. While data[i] <= data[pivot]++i

2. While data[j] > data[pivot]--j

3. If i < jswap data[i] and data[j]

4. While j > i, go to 1.

[0] [1] [2] [3] [4] [5] [6] [7] [8]

Sathi Durga Devi, Dept of IT

Page 81: Unit iv(dsc++)

40 20 10 30 60 50 7 80 100pivot_index = 0

i j

1. While x[i] <= x[pivot]++i

2. While x[j] >x[pivot]--j

3. If i < jswap x[i] and x[j]

4. While j > i, go to 1.

[0] [1] [2] [3] [4] [5] [6] [7] [8]

Sathi Durga Devi, Dept of IT

Page 82: Unit iv(dsc++)

1. While x[i] <= x[pivot]++i

2. While x[j] > x[pivot]--j

3. If i < jswap x[i] and x[j]

4. While j > i, go to 1.

40 20 10 30 7 50 60 80 100pivot_index = 0

i j

[0] [1] [2] [3] [4] [5] [6] [7] [8]

Sathi Durga Devi, Dept of IT

Page 83: Unit iv(dsc++)

1. While x[i] <= x[pivot]++i

2. While x[j] > x[pivot]--j

3. If i < jswap x[i] and x[j]

4. While j > i, go to 1.

40 20 10 30 7 50 60 80 100pivot_index = 0

i j

[0] [1] [2] [3] [4] [5] [6] [7] [8]

Sathi Durga Devi, Dept of IT

Page 84: Unit iv(dsc++)

1. While x[i] <= x[pivot]++i

2. While x[j] > x[pivot]--j

3. If i < jswap x[i] and x[j]

4. While j > i, go to 1.

40 20 10 30 7 50 60 80 100pivot_index = 0

i j

[0] [1] [2] [3] [4] [5] [6] [7] [8]

Sathi Durga Devi, Dept of IT

Page 85: Unit iv(dsc++)

1. While x[i] <= x[pivot]++i

2. While x[j] > x[pivot]--j

3. If i < jswap x[i] and x[j]

4. While j > i, go to 1.

40 20 10 30 7 50 60 80 100pivot_index = 0

i j

[0] [1] [2] [3] [4] [5] [6] [7] [8]

Sathi Durga Devi, Dept of IT

Page 86: Unit iv(dsc++)

1. While data[i] <= data[pivot]++i

2. While data[j] > data[pivot]--j

3. If i < jswap data[i] and data[j]

4. While j > i, go to 1.

40 20 10 30 7 50 60 80 100pivot_index = 0

i j

[0] [1] [2] [3] [4] [5] [6] [7] [8]

Sathi Durga Devi, Dept of IT

Page 87: Unit iv(dsc++)

1. While data[i] <= data[pivot]++i

2. While data[j] > data[pivot]--j

3. If i < jswap data[i] and data[j]

4. While j > i, go to 1.

40 20 10 30 7 50 60 80 100pivot_index = 0

i j

[0] [1] [2] [3] [4] [5] [6] [7] [8]

Sathi Durga Devi, Dept of IT

Page 88: Unit iv(dsc++)

1. While x[i] <= x[pivot]++i

2. While x[j] > x[pivot]--j

3. If i < jswap x[i] and x[j]

4. While j > i, go to 1.

40 20 10 30 7 50 60 80 100pivot_index = 0

i j

[0] [1] [2] [3] [4] [5] [6] [7] [8]

Sathi Durga Devi, Dept of IT

Page 89: Unit iv(dsc++)

1. While x[i] <= x[pivot]++i

2. While x[j] > x[pivot]--j

3. If i < jswap x[i] and x[j]

4. While j > i, go to 1.

40 20 10 30 7 50 60 80 100pivot_index = 0

i j

[0] [1] [2] [3] [4] [5] [6] [7] [8]

Sathi Durga Devi, Dept of IT

Page 90: Unit iv(dsc++)

1. While x[i] <= x[pivot]++i

2. While x[j] > x[pivot]--j

3. If i < jswap x[i] and x[j]

4. While j > i, go to 1.

40 20 10 30 7 50 60 80 100pivot_index = 0

i j

[0] [1] [2] [3] [4] [5] [6] [7] [8]

Sathi Durga Devi, Dept of IT

Page 91: Unit iv(dsc++)

1. While x[i] <= x[pivot]++i

2. While x[j] > x[pivot]--j

3. If i < jswap x[i] and x[j]

4. While j > i, go to 1.5. Swap x[j] and x[pivot_index]

40 20 10 30 7 50 60 80 100pivot_index = 0

i j

[0] [1] [2] [3] [4] [5] [6] [7] [8]

Sathi Durga Devi, Dept of IT

Page 92: Unit iv(dsc++)

1. While x[i] <= x[pivot]++i

2. While x[j] > x[pivot]--j

3. If i < jswap x[i] and x[j]

4. While j > i, go to 1.5. Swap x[j] and x[pivot_index]

7 20 10 30 40 50 60 80 100pivot_index = 4

[0] [1] [2] [3] [4] [5] [6] [7] [8]

i j

Sathi Durga Devi, Dept of IT

Page 93: Unit iv(dsc++)

Partition Result

7 20 10 30 40 50 60 80 100

[0] [1] [2] [3] [4] [5] [6] [7] [8]

<= data[pivot] > data[pivot]

Sathi Durga Devi, Dept of IT

Page 94: Unit iv(dsc++)

Recursion: Quicksort Sub-arrays

7 20 10 30 40 50 60 80 100

[0] [1] [2] [3] [4] [5] [6] [7] [8]

<= data[pivot] > data[pivot]

Sathi Durga Devi, Dept of IT

Page 95: Unit iv(dsc++)

• Example 44,33,11,55,77,90,40,60,99,22,66

Sathi Durga Devi, Dept of IT

Page 96: Unit iv(dsc++)

Average Case

Worst Case

Linear Search - O(n)Binary Search O(log n) O(n)Bubble Sort O(n2) O(n2)Selection Sort - O(n2)Insertion Sort - O(n2)Merge Sort O(n log n) O(n log n) Quick Sort O(n log n) O(n2)

Time Complexities of Searching & Sorting Algorithms:

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.

Sathi Durga Devi, Dept of IT

Page 97: Unit iv(dsc++)

• 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.

Review of Algorithms

Sathi Durga Devi, Dept of IT

Page 98: Unit iv(dsc++)

Assignment - 2

1. Write and explain the breath first traversal and depth first traversal in a graph with algorithm

2. Write notes on spanning tree. Write and explain the algorithms to find minimal cost.

3. Write recursive functions in C for preorder, inorder and post order traversals of a binary tree.

4. Explain with an example how an element is deleted from a binary search tree.5. Construct the binary search for the following data 32, 12,45,6,78,24,33,9,53,36. Write a c program to implement the non recursive method for binary search.7. Write a c program to implement the quick sort. sort the given elements using quick sort 40,20,10,80,60,50,7,30,100.8. Explain the procedure for merge sort. Write the time complexities for various

searching and sorting techniques.

Sathi Durga Devi, Dept of IT