searching, sorting, stack, queue, lists u n i t 5 p a g e...
Post on 02-May-2019
215 Views
Preview:
TRANSCRIPT
Searching, Sorting, Stack, Queue, Lists U N I T 5 P a g e | 1
UNIT V SEARCHING & SORTING, STACKS, QUEUES, LISTS
Searching and Sorting – Sorting- selection sort, bubble sort, Searching-linear and binary search methods.
Lists- Linear list – singly linked list implementation, insertion, deletion and searching operations on linear list, StacksPushand Pop Operations, Queues- Enqueue and Dequeue operations.
SEARCHING & SORTING
In this chapter we will discuss about two common array procedures: Searching & Sorting. Very common operation in computer science in “Searching”. A Searching is a process used to find
the location of a target element among a list of objects. The search is claimed as successful or unsuccessful depending on whether the targeted element is
found or not. There are two types of searching techniques.
1. Linear Search or Sequential Search 2. Binary Search
Linear / Sequential search: The Sequential search is used whenever the list is unordered. Generally we use this technique only small lists or lists that are not searched often. This simplest method can be used either for sorted or unsorted list of elements. We start searching for the target from the beginning of the list, and we continue until we find the target or until we are sure that it is not there in the list. Ex: Assume the listed elements, in which we would like to search the element 56. The element 56 is compared with each of the element from beginning. Once the element is found then it stops searching. Time Complexity: The Number of machine instructions which a program executes during its running time is called its “time complexity”. This number depends primarily on the size of the program’s input. Time taken by a program is the sum of the compile time and runtime. In the time complexity, we consider run time only. Space Complexity: The space complexity of an algorithm (for a given input) is the number of elementary objects that this algorithm needs to store during its execution. This number computed with respect to the size of the input data. The space occupied by an algorithm is determined by the number and sizes of the variables and data structures used by the algorithm. Efficiency of Linear Search:
Linear search works with an efficiency of O(N) for N number of elements in the list. If the data are distributed randomly, an average of N/2comparison is needed. The worst case is that the value is not there in the list or it is the last element, which takes n comparisons to search.
Computer Programming U N I T 5 P a g e | 2
/*PROGRAM TO IMPLEMENT LINEAR SEARCH*/
#include<stdio.h>
void main()
{
int a[10],i,key,n;
clrscr();
printf("\nHow many Elements you want to Enter? ");
scanf("%d",&n);
printf("\nEnter the Key element to search! ");
scanf("%d",&key);
printf("\nEnter the elements: ");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=0;i<n;i++)
{
if(a[i]==key)
{
printf("\nElement found in position %d ",i+1);
getch();
exit(1);
}
}
printf("\nElement %d not Found",key);
getch();
}
O/P:
How many Elements you want to Enter? 6
Enter the Key element to search! 56
Enter the elements: 23 67 89 56 19 12
Element found in position 4
==============================================================================
Searching, Sorting, Stack, Queue, Lists U N I T 5 P a g e | 3
BINARY SEARCH: The most efficient technique that can be applied to list of sorted elements is Binary Search. This technique is faster than the other searching techniques. In this method, the given sorted list of elements will be divided into three parts. The first element is treated as low and last as high, if low is less than high then a mid will be considered by taking (low+mid)/2. The key is first compared with the middle record(mid). If the match is found, the key index is returned. If it is doesn’t match, then the required key must be either in the left half or right half of the middle.If the key is less than the middle record, the key is searched in the left part, else it is checked in the right part of the middle element.
Efficiency of Binary Search: The binary search algorithm is having the efficiency of O (log2n)
Computer Programming U N I T 5 P a g e | 4
/*PROGRAM TO IMPLEMENT THE BINARY SEARCH ALGORITHM-NON-RECURSIVE*/
void main()
{
int a[10],i,key,n,low,mid,high;
clrscr();
printf("\nHow many Elements you enter? ");
scanf("%d",&n);
printf("\nEnter the Key Element to search ");
scanf("%d",&key);
printf("\nEnter the Elements ascending order: ");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
low=0;
high=n-1;
while(low<=high)
{
mid=(low+high)/2;
if(key==a[mid])
{
printf("\nElement found in %d position",mid+1);
getch();
exit();
}
else
if(key<a[mid])
high=mid-1;
else
low=mid+1;
}
printf("\nElement %d not found",key);
getch();
}
O/P:
How many Elements you enter? 6
Enter the Key Element to search 10
Enter the Elements ascending order: 5 7 9 10 12 15
Element found in 4 position
Note: if the elements entered by the user are distinct then the above code gives the position of occurrence
of the no. if some of them are repeated then it may give be any position of the same no., but may not be the
first occurrence
------------------------------------------------------------------------
Searching, Sorting, Stack, Queue, Lists U N I T 5 P a g e | 5
/*PROGRAM TO IMPLEMENT THE BINARY SEARCH ALGORITHM USING RECURSION*/
int key;
int binary(int[],int,int);
void main()
{
int a[10],i,n,p;
clrscr();
printf("\nHow many Elements you enter? ");
scanf("%d",&n);
printf("\nEnter the Key Element to search ");
scanf("%d",&key);
printf("\nEnter the Elements: ");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
p=binary(a,0,n-1);
if(p==0)
printf("\nElement not Found");
else
printf("\nElement Found in %d position",p);
getch();
}
binary(int a[10],int low, int high)
{
int mid;
if(low<=high)
{
mid=(low+high)/2;
if(key==a[mid])
return mid+1;
else
if(key<a[mid])
binary(a,low,mid-1);
else
binary(a,mid+1,high);
}
else
return 0;
}
O/P:
How many Elements you enter? 6
Enter the Key Element to search 8
Enter the Elements: 2 4 6 8 10 12
Element Found in 4 position. ========================================================================
Computer Programming U N I T 5 P a g e | 6
22( 1)
( 1) ( 2) ( 3) ... 2 1 ( )2 2
n n n nn n n O n
SORTING: The process through which data are arranged according to their values in some order is called Sorting. These are very common applications in computer science. We have the following sorting techniques
1. Bubble Sort 2. Selection Sort 3. Insertion Sort 4. Merge Sort 5. Quick Sort
BUBBLE SORT / EXCHANGE SORT: The way of putting the largest element at the highest index in the array uses an algorithm called
Bubble sort. In this sorting technique the adjacent elements are compared and exchanged if they are not in
order. If there are n elements then there will be n-1 passes or iterations. During the first pass the first and second elements are compared and swapped if they are not in
order. Next, the 2nd, 3rd and 3rd, 4th and so on are compared and the process will be repeated until
comparison of all the elements is finished. After the first pass the largest element will move to its correct position i.e. the last position. The same process will be repeated for the next passes. Bubble sort is very inefficient and should only be used on small data sets.
Algorithm for i<-0 to n-1 do for j <-0 to n-1-i do if (a[j] > a[j+1]) then
Exchange a[j] <-> a[j+1]. This algorithm needs n-1 iterations for n no. of elements. In the first iteration we do n-1 comparisons among n elements and in the second iteration we need n-2 comparisons among n-1 elements and so on one comparison among 2 elements. So total no. of comparisons are
Complexity can be expressed by using Big-oh (O) notation, i.e., O(n2) The time complexity can be expressed by using the three cases
Best Case: The minimum number of comparisons needed to sort.
Average Case: The Average number of comparisons needed to sort
Worst Case: The maximum number of comparisons needed to sort.
In all cases the time complexity of Bubble sort algorithm is2( )O n .
Searching, Sorting, Stack, Queue, Lists U N I T 5 P a g e | 7
Implementation of Bubble Sort
BUBBLE SORT
Initial Elements
23 67 89 56 19 12
PASS 0 (Iteration1)
23 67 89 56 19 12
23 67 89 56 19 12
23 67 89 56 19 12
23 67 56 89 19 12
23 67 56 19 89 12
23 67 56 19 12 89
PASS 1 (Iteration2)
23 67 56 19 12 89 is the largest
element 23 67 56 19 12
23 56 67 19
23 56 19 67 12
23 56 19 12 67
PASS 2 (Iteration3)
23 56 19 12 67 is the Second largest
element
23 56 19 12
19 56 12
23 19 12 56
PASS 3 (Iteration4)
23 19 12 56 is the Next largest
element
19 23 12
19 12 23 PASS 4
(Iteration5)
19 12 Next is 23 12 19
FINAL 12 19 23 56 67 89
Computer Programming U N I T 5 P a g e | 8
/*PROGRAM TO IMPLEMENT BUBBLE SORT*/
void main()
{
int a[10],i,n,f,j,t,k;
clrscr();
printf("\nHow many no.s you enter?");
scanf("%d",&n);
printf("\nEnter elements in order ");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=0;i<n;i++)
{
f=0;
/*printf("\n pass %d: ",i); remove comments to see the iteration no.s*/
for(j=0;j<n-i-1;j++)
{
if(a[j]>a[j+1])
{
f=1;
t=a[j];
a[j]=a[j+1];
a[j+1]=t;
}
/* REMOVE COMMENTS TO SEE THE PROCESS
for(k=0;k<n;k++)
{
printf(" %d",a[k]);
}
printf("\n"); */
}
if(f==0)
break;
}
printf("\n Sorted elements are: \n");
for(i=0;i<n;i++)
printf("\t%d",a[i]);
getch();
}
O/P:
How many no.s you enter?6
Enter elements: 23 67 89 56 19 12
Sorted elements are: 12 19 23 56 67 89 ===================================================================
Searching, Sorting, Stack, Queue, Lists U N I T 5 P a g e | 9
SELECTION SORT: This is the simplest method of sorting. In this to sort the data in ascending order, the 1st element is compared with all the other elements. If the 1st element is found to be greater than the compared element then they are interchanged. So after the first iteration the smallest element is placed at the 1st position. The same procedure is repeated for the 2nd, 3rd elements and so on. After the selection sort the best element from the data set , for the given
Algorithm:
For i<-1 to n-1 do
For j-<i+1 to n-1 do
If a[i] > a[j] Exchange a[i] and a[j];
Efficiency of Selection Sort:
Here also same discussion takes as in the Bubble sort and the efficiency in all cases is O(n2)
Computer Programming U N I T 5 P a g e | 10
/*PROGRAM TO IMPLEMENT THE SELECTION SORT*/
void main()
{
int a[10],i,j,n,t;
clrscr();
printf("How many Element you enter?");
scanf("%d",&n);
printf("\nEnter the elements");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]>a[j])
{
t=a[i];
a[i]=a[j];
a[j]=t;
}
}
}
printf("\nSorted Elements are:");
for(i=0;i<n;i++)
printf(" %d",a[i]);
getch();
}
O/P:
How many Element you enter?6
Enter the elements: 23 67 89 56 8 12
Sorted Elements are: 8 12 23 56 67 89
================================================================
Searching, Sorting, Stack, Queue, Lists U N I T 5 P a g e | 11
Internal Sorting: An internal sort is any data sorting process that takes place entirely within the main memory of a computer. This is possible whenever the data to be sorted is small enough to all be held in the main memory. For sorting larger datasets, it may be necessary to hold only a chunk of data in memory at a time, since it won’t all fit. The rest of the data is normally held on some larger, but slower medium, like a hard-disk. Internal Sorting algorithms are of following types: Bubble Sort, Insertion Sort, Quick Sort, Heap Sort, merge Sort, Radix Sort, Selection sort.
External sorting: External sorting is a term for a class of sorting algorithms that can handle massive amounts of data. External sorting is required when the data being sorted do not fit into the main memory of a computing device (usually RAM) and instead they must reside in the slower external memory (usually a hard drive). External sorting typically uses a sort-merge strategy. In the sorting phase, chunks of data small enough to fit in main memory are read, sorted, and written out to a temporary file. In the merge phase, the sorted sub files are combined into a single larger file. External Sorting algorithms are of following types: K-way Merge Sort, Multi-way / k-way merge sort, Balanced Merge Sort, Poly-Phase Merge Sort Need of External Sorting: Entire data to be sorted might not fit in the available internal memory Considerations When data resides in internal memory Data access time << Computation time Need to reduce the number of CPU operations When data resides on external storage devices Data access time >> Computation time Need to reduce disk accesses Difference between internal and external sorting: Internal Sorting takes place in the main memory of a computer. The internal sorting methods are applied to small collection of data. It
means that, the entire collection of data to be sorted in small enough that the sorting can take place within main memory. The External sorting methods are applied only when the number of data elements to be sorted is too large. These methods involve as
much external processing as processing in the CPU. This sorting requires auxiliary storage. Internal sorting takes small input, whereas external sorting can take as much as large input... The following is the list that illustrates the time complexities of various algorithms.
NAME TIME COMPLEXITY SPACE COMPLEXITY BEST AVERAGE WORST
SORT
BUBBLE O(n) O(n2) O(n2) O(n)
INSERTION O(n) O(n2) O(n2) O(n)
SELECTION O(n2) O(n2) O(n2) O(n)
QUICK O(logn) O(nlogn) O(n2) O(n + log n)
MERGE O(nlogn) O(nlogn) O(nlogn) O(2n)
HEAP O(nlogn) O(nlogn) O(nlogn) O(n)
SEARCH
LINEAR O(n) O(1) O(n)
BINARY O(nlogn) O(nlogn) O(nlogn)
================================================================================= {RK Notes: At each iteration, the length of the new sub array to be searched is approximately half of the previous one.
If n = 2k+m, where 0 m < 2k, then n can be split approximately in half k times.
Since 2k n < 2k+1, then k = log2n (by proposition 1)
Thus, the number of iterations of the while loop in a worst-case execution of the algorithm is log2n+1. The number of operations in each loop is constant (doesn’t increase with n).
Thus, the binary search algorithm is O(log2n)
Proposition 1: If k is an integer and x is a real number with 2k x < 2k+1, then log2x = k .
Proof: 2k x < 2k+1
log2(2k) log2(x) < log2(2k+1) (since log2x increasing)
k log2(x) < k+1 (by definition of log2x)
log2x = k (by definition of floor function). } ==================================================================================
Computer Programming U N I T 5 P a g e | 12
JNTUH-DESCRIPTIVE/ASSIGNMENT QUESTIONS
JUN2012, JUN2011 & MAY-DEC 2010 (4 sets from each year) JUN2012
1) a) Write a C program for binary search using recursion to find a given integer in an array of n elements.
b) Illustrate the results for each pass of selection sort, for the following array of elements 2, 3, 78, 5, 46, 32, 56, 8, 100, 9.
JUN2011
2) Explain bubble sort with the algorithm or a C program.
3) Illustrate the results of bubble sort for each pass, for the following initial array of elements:
68 67 99 33 122 200
4) Write a C program or algorithm to sort an array of integers in ascending order using insertion sort.
5) Illustrate the results of insertion sort for each pass, for the following initial array of elements:
68 57 99 33 122 200
6) Write an algorithm or C program for sorting integers in ascending order using selection sort.
7) Illustrate the results for each pass of selection sort, for the following the initial array of elements:
23 78 45 8 32 56
8) Write an algorithm or program for binary search to find a given integer in an array of integers.
9) Illustrate the results of bubble sort for each pass, for the following initial array of elements:
44 36 57 19 25 89 28
MAY-DEC 2010
10) Write an algorithm or C-program for sorting integers in ascending order using insertion sort.
11) Demonstrate the insertion sort results for each insertion for the following initial array of elements. 25 6 15 12
8 34 9 18 2
12) Write an algorithm or program for sorting integers using bubble sort.
13) Show the bubble sort results for each pass for the following initial array of elements.
35 18 7 12 5 23 16 3 1
14) Write an algorithm or C-function for selection sort for sorting an array of integer in ascending order.
15) Demonstrate the selection sort results for each pass for the following initial array of elements.
21 6 3 57 13 9 14 18 2
16) Write algorithm/Program for binary search to find the given element within array. For What data binary search is not
applicable?
17) Show the quick sort results for each exchange for the following initial array of elements
35 54 12 18 23 15 45 38
18) Write a C program for binary search using functions without using recursion?
19) An array contains 8, 13, 17, 26, 44, 56, 88, and 97. Trace the steps using binary search Algorithm.
a. To find value 88
b. To find the value 20
c. To find the value 8.
20) Write a C program for insertion sort using functions?
21) An Array contains 47, 3, 66, 32, 56, and 92. After two passes of a sorting algorithm, the array has been rearranged to:
3, 47, 66, 32, 56, and 92. Which sorting algorithm among selection, insertion, and bubble sort is used? Defend your
answer?
22) Write a C program for bubble sort using functions?
23) An Array contains 3, 13, 7, 26, 44, 23, 98, and 57. Trace the steps using merge sort?
24) Write a C program for selection sort using functions?
25) An Array contains 3, 13, 7, 26, 44, 23, 98, and 57. Trace the steps using quick sort?
26) Write a ‘c’ program to sort the given integers using partition Exchange sort?
27) Write a ‘c’ program to search for a given element in the integer array using binary search.
28) Explain Linear search method with an example.
29) Explain Binary search method with an example.
30) Write a recursive binary search function to find the location of the given element in the array.
31) What is the difference between sorting and searching?
32) Explain the algorithm for exchange sort with a suitable example.
Searching, Sorting, Stack, Queue, Lists U N I T 5 P a g e | 13
JAWAHARLAL NEHRU TECHNOLOGICAL UNIVERSITY HYDERABAD I B.Tech III Mid-Term Examinations, April/May-2012
COMPUTER PROGARMMING AND DATA STRUCTURES I. Choose the correct alternatives: 1. Find out the internal Sorting methods
(A)bubble sort (B)insertion sort (C )selection sort (D)All
2. The algorithms having complexity of O(n), O(n2) are known as (A)sophisticated algorithms (B)Simple algorithms (C)deterministic algorithms (D)All
3. Which one of the following operation returns a pointer to a temporary file (A) tmpfile() (B)fprint() (C)vprint() (D)freturn() 4. fscanf() reads __________ byte input from stdin,a file stream or a buffer (A)direct (B)unformatted (C)Formatted (D)None 5. ‘rewind()’ is which type of operations in files (A) file I/O (B)formatted I/O (C) file status (D) standard I/O 6. which one of the following is the return type of ‘ftell()’ (A) Int (B)Void (C) Long (D)None 7. Which one of the following returns the number of elements on the stack (A) get-size():Float (B)get-size():Integer (C) top():item-type (D) All 8. What is the disadvantage of linked list (A) slow search (B) fixed size (C) slow insertion (D)All 9. What is the Best case performanceof the quick sort (A) O(n log n) (B) O(n) (C) O(n) (D) None
10. Best case performance of Binary search is (A) O(n2) (B)O(1) (C)O(n log n) (D) None
II. Fill in the blanks 11. C has no direct support for _______________ data files. 12. External sorting methods are applied on large sets of data which reside on ____________devices. 13. ______________ checks for a file error. 14. Stack is very similar to a list except that a stack is more _____________. 15. _____________ nodes are added to the rear end of the queue. 16. A ____________ search is also called as half-internal search. 17. Two stacks are used to implement a _____________. 18. Many complex applications can be easily carried out with _____________. 19. A ________________ sort is a sort algorithm that returns the same results each time 20. _________________ sorting technique is also called as exchange sort.
Computer Programming U N I T 5 P a g e | 14
DATA STRUCTURES In computer science, a data structure is a particular way of storing and organizing data in
a computer so that it can be used efficiently. Data structures are used in almost every program or software system. Data structures
provide a means to manage huge amounts of data efficiently, such as large databases and internet indexing services.
A List is a collection of related data. We can divide lists into two categories: Linear lists
and non-linear lists. Linear lists divided into general lists, stacks, and queues. Non-linear lists divided into trees and graphs.
In this section, we learn the linear lists. As the linear lists are useful structures, programmers use them in many applications, Rather than rewrite their functions each time we need them we can write the functions once and put them in a library. Then when we need to use a linear list, we simply include the library. The name given to complete set of functions built like this is Abstract Data Type(ADT).
“A Data Structure is a collection of elements and the relationships among them. Data structures can be nested. That is, we can have a data structure that contains of other data structures.”
Array:
A Homogeneous combination of data structures. Position association.
Structure:
A heterogeneous combination of data structures. No association
Searching, Sorting, Stack, Queue, Lists U N I T 5 P a g e | 15
STACK: A stack is a last in, first out (LIFO) abstract data type and data structure. A stack can have any abstract data type as an element, but is characterized by only three
fundamental operations: push, pop and stack top. The push operation adds a new item to the top of the stack, or initializing the stack if it is
empty, but if the stack is full and does not contain more space to accept the given item it is considered as an Overflow state (It means that the stack is overloaded or no more space for new item).
The pop operation removes an item from the top of the stack, A pop either reveals previously concealed items, or results in an empty stack, but if the stack is empty then it goes into underflow state (It means no items are present in stack to be removed).
The stack top operation gets the data from the top-most position and returns it to the user without deleting it.
The same underflow state can also occur in stack top operation if stack is empty. A stack is a restricted data structure, because only a small number of operations are performed on it. The nature of the pop and push operations also mean that stack elements have a natural order. Elements are removed from the stack in the reverse order to the order of their addition: therefore, the lower elements are those that have been on the stack the longest.
* A stack is a list with the restriction That insertions and deletions can only be
performed at the top of the list The other end is called bottom
* Fundamental operations:
Push: Equivalent to an insert Pop: Deletes the most recently inserted
element Top: Examines the most recently inserted
element
Computer Programming U N I T 5 P a g e | 16
Stack-Array Implementation
• Need to declare an array size ahead of time • Associated with each stack is TopOfStack
– for an empty stack, set TopOfStack to -1 • Push
– (1) Increment TopOfStack by 1. – (2) Set Stack[TopOfStack] = X
• Pop – (1) Set return value to Stack[TopOfStack] – (2) Decrement TopOfStack by 1
• These operations are performed in very fast constant time ALGORITHM:-WRITE A PROGRAM FOR THE ARRAY IMPLEMENTATION OF STACK. PUSH:- 1.if(top==max-1) 1.print(stack overflow) 2.else 1.top=top+1 2.stack arr[top]=pushed item 3.endif end algorithm POP:- 1.if (top==-1) 1.print(stack underflow) 2.else 1.print(popped element is stack arr[top]) 2.top=top-1 3.end if end algorithm
Searching, Sorting, Stack, Queue, Lists U N I T 5 P a g e | 17
/*PROGRAM TO IMPLEMENT STACK ADT
USING ARRAYS*/
#include<stdio.h>
#define MAX 5
int stack[MAX],top=-1;
main()
{
int ch;
printf("\n1.Push\t2.Pop\t3.Display\t4.Exit");
while(1)
{
printf("\nEnter Your Choice");
scanf("%d",&ch);
switch(ch)
{
case 1:push();break;
case 2:pop();break;
case 3:display();break;
case 4:exit();
default: printf("\nWrong Choice");
}
}
}
push()
{
int x;
if(top==MAX-1)
{
printf("\nStack is Overflow(FULL)");
}
else
{
printf("Enter element to be pushed:");
scanf("%d",&x);
top++;
stack[top]=x;
}
}
pop()
{
int p;
if(top==-1)
{
printf("\nStack is Underflow(EMPTY)");
}
else
{
p=stack[top];
top--;
printf("\nPopped Element is %d",p);
}
}
display()
{
int i;
if(top==-1)
{
printf("\nStack is Underflow(EMPTY)");
}
else
{
for(i=top;i>=0;i--)
{
printf("\n%d",stack[i]);
}
}
}
Output:
1.Push 2.Pop 3.Display 4.Exit
Enter Your Choice3
Stack is Underflow(EMPTY)
Enter Your Choice1
Enter element to be pushed: 22
Enter Your Choice1
Enter element to be pushed: 4
Enter Your Choice1
Enter element to be pushed: 66
Enter Your Choice1
Enter element to be pushed: 33
Enter Your Choice1
Enter element to be pushed: 88
Enter Your Choice1
Stack is Overflow (FULL)
Enter Your Choice
Stack is Overflow (FULL)
Enter Your Choice2
Popped Element is 88
Enter Your Choice2
Popped Element is 33
Enter Your Choice3
66
44
22
Enter Your Choice2
Popped Element is 66
Enter Your Choice2
Popped Element is 44
Enter Your Choice2
Popped Element is 22
Enter Your Choice3
Stack is Underflow (EMPTY)
Enter Your Choice4
Computer Programming U N I T 5 P a g e | 18
QUEUE: Like a stack, a queue is also a list. However, with a queue, insertion is done at
one end, while deletion is performed at the other end. Accessing the elements of queues follows a First In, First Out (FIFO) order.
Ex:Like customers standing in a check-out line in a store, the first customer in is the first customer served.
Basic operations: Enqueue : Insert an element at the rear of the queue Dequeue : Remove an element from the front of the queue.
*Queue using Arrays:*/
Algorithm: AIM:- WRITE A PROGRAM FOR ARRAY IMPLEMENTATION OF QUEUE. ALGORITHM:- ENQUEUE:- if(rear==(MAX-1))
print (queue overflow) else if (front==-1) front=0 rear=rear+1 queue_arr[rear]=added_item endif
DEQUEUE:- if(front==-1 OR front>rear) print(queue underflow) else print(element deleted from queue, queue_arr[front]) front=front+1 end if end algorithm
Searching, Sorting, Stack, Queue, Lists U N I T 5 P a g e | 19
/*PROGRAM TO IMPLEMENT QUEUE ADT
USING ARRAYS*/
#include<stdio.h>
#define MAX 5
int queue[MAX],front=-1,rear=-1;
main()
{
int ch;
clrscr();
printf("\t1.Insert");
printf("\t2.Delete");
printf("\t3.Display");
printf("\t4.Exit");
while(1)
{
printf("\nEnter Your Choice");
scanf("%d",&ch);
switch(ch)
{
case 1: insert(); break;
case 2: delete(); break;
case 3: display(); break;
case 4: exit();
default: printf("\n Wrong Choice!, Enter
Correct option") ;
}
}
}
insert()
{
int x;
if(rear==MAX-1)
{
printf("\nQueue is Full");
}
else
{
if(front==-1)
front=0;
printf("Enter element to be
inserted");
scanf("%d",&x);
rear++;
queue[rear]=x;
}
}
delete()
{
int p;
if(front==-1||front==rear+1)
{
printf("\nQueue is empty");
}
else
{
p=queue[front];
front++;
printf("\nDeleted Element is
%d",p);
}
}
display()
{
int i;
if(front==-1||front==rear+1)
{
printf("\nQueue is empty");
}
else
{
for(i=front;i<=rear;i++)
{
printf("\t%d",queue[i]);
}
}
}
Output:
Queue Choice Menu:
1.Insert 2.Delete 3.Display 4.Exit
Enter Your Choice1
Enter element to be inserted11
Enter Your Choice1
Enter element to be inserted33
Enter Your Choice1
Enter element to be inserted22
Enter Your Choice1
Enter element to be inserted55
Enter Your Choice1
Enter element to be inserted66
Enter Your Choice1
Queue is Full
Enter Your Choice3
11 33 22 55 66
Enter Your Choice2
Deleted Element is 11
Enter Your Choice2
Deleted Element is 33
Enter Your Choice2
Deleted Element is 22
Computer Programming U N I T 5 P a g e | 20
Enter Your Choice2
Deleted Element is 55
Enter Your Choice2
Deleted Element is 66
Enter Your Choice2
Queue is empty
Enter Your Choice1
Queue is Full
Enter Your Choice3
Queue is empty
Enter Your Choice4
Note: Observe the situation where Queue became
Full(
Infact no scope to insert elements) as well as Empty.
Searching, Sorting, Stack, Queue, Lists U N I T 5 P a g e | 21
LINKED LISTS: • A linked list is a series of connected
nodes. • Each node contains at least
– A piece of data (any type) – Pointer to the next node in the list
• Head: pointer to he first node. • The last node points to NULL.
Computer Programming U N I T 5 P a g e | 22
Single Linked List: #include<stdio.h>
struct node
{
int data;
struct node *next;
};
struct node *head=NULL,*temp,*n;
main()
{
int x,ch;
do
{
temp=(struct node
*)malloc(sizeof(structnode));
printf("\nEnter the element to be
inserted");
scanf("%d",&x);
temp->data=x;
temp->next=NULL;
if(head==NULL)
{
head=temp;
}
else
{
n=head;
while(n->next!=NULL)
n=n->next;
n->next=temp;
}
}while(x!=999);
while(1)
{
printf("\n1.Insert");
printf("\n2.Delete");
printf("\n3.Display");
printf("\n4.Exit");
printf("\nEnter Your Choice");
scanf("%d",&ch);
switch(ch)
{
case 1:insert();
break;
case 2:delet();
break;
case 3:display();
break;
case 4:exit();
default:printf("\nWrong Option, Select
other choice");
}
}
}
insert()
{
int p,x,c,i;
temp=(struct node *)malloc(sizeof(struct
node));
printf("\nEnter the element to be
inserted");
scanf("%d",&x);
temp->data=x;
temp->next=NULL;
printf("\nEnter the position to be
inserted");
printf("\n1.Beginning");
printf("\n2.Middle");
printf("\n3.End");
printf("\nEnter your option");
scanf("%d",&p);
if(p==1)
{
temp->next=head;
head=temp;
}
else
if(p==2)
{
n=head;
printf("\nEnter the exact place to be
inserted");
scanf("%d",&c);
for(i=1;i<c-1;i++)
{
n=n->next;
}
temp->next=n->next;
n->next=temp;
}
Searching, Sorting, Stack, Queue, Lists U N I T 5 P a g e | 23
else
if(p==3)
{
n=head;
while(n->next->data!=999)
n=n->next;
temp->next=n->next;
n->next=temp;
}
}
delet()
{
int p,c;
printf("\nEnter the position to be deleted
from");
printf("\n1.Beginning");
printf("\n2.Middle");
printf("\n3.End");
printf("\nEnter your choice");
scanf("%d",&p);
if(p==1)
{
temp=head;
printf("\nDeleted node value is %d",temp-
>data);
head=head->next;
free(temp);
}
else
if(p==2)
{
n=head;
printf("\nEnter the exact node to be
deleted");
scanf("%d",&c);
while(n->next->data!=c)
n=n->next;
temp=n->next;
printf("\nDeleted node value is %d",temp-
>data);
n->next=temp->next;
free(temp);
}
else
if(p==3)
{
n=head;
while(n->next->next->data!=999)
n=n->next;
temp=n->next;
printf("\nDeleted node value is %d",temp-
>data);
n->next=n->next->next;
free(temp);
}
}
display()
{
n=head;
while(n->next!=NULL)
{
printf("%d->",n->data);
n=n->next;
}
}
Output:
Enter the element to be inserted1
Enter the element to be inserted2
Enter the element to be inserted3
Enter the element to be inserted4
Enter the element to be inserted5
Enter the element to be inserted999
1.Insert
2.Delete
3.Display
4.Exit
Enter Your Choice3
1->2->3->4->5->
1.Insert
2.Delete
3.Display
4.Exit
Enter Your Choice1
Enter the element to be inserted6
Enter the position to be inserted
1.Beginning
2.Middle
3.End
Enter your option1
1.Insert
2.Delete
Computer Programming U N I T 5 P a g e | 24
3.Display
4.Exit
Enter Your Choice3
6->1->2->3->4->5->
1.Insert
2.Delete
3.Display
4.Exit
Enter Your Choice1
Enter the element to be inserted7
Enter the position to be inserted
1.Beginning
2.Middle
3.End
Enter your option2
Enter the exact place to be inserted3
1.Insert
2.Delete
3.Display
4.Exit
Enter Your Choice3
6->1->7->2->3->4->5->
1.Insert
2.Delete
3.Display
4.Exit
Enter Your Choice1
Enter the element to be inserted8
Enter the position to be inserted
1.Beginning
2.Middle
3.End
Enter your option3
1.Insert
2.Delete
3.Display
4.Exit
Enter Your Choice3
6->1->7->2->3->4->5->8->
1.Insert
2.Delete
3.Display
4.Exit
Enter Your Choice2
Enter the position to be deleted from
1.Beginning
2.Middle
3.End
Enter your choice1
Deleted node value is 6
1.Insert
2.Delete
3.Display
4.Exit
Enter Your Choice3
1->7->2->3->4->5->8->
1.Insert
2.Delete
3.Display
4.Exit
Enter Your Choice2
Enter the position to be deleted from
1.Beginning
2.Middle
3.End
Enter your choice2
Enter the exact node to be deleted7
Deleted node value is 7
1.Insert
2.Delete
3.Display
4.Exit
Enter Your Choice3
1->2->3->4->5->8->
1.Insert
2.Delete
3.Display
4.Exit
Enter Your Choice2
Enter the position to be deleted from
1.Beginning
2.Middle
3.End
Enter your choice3
Deleted node value is 8
1.Insert
2.Delete
3.Display
4.Exit
Enter Your Choice3
1->2->3->4->5->
1.Insert
2.Delete
3.Display
4.Exit
Enter Your Choice: 4
Searching, Sorting, Stack, Queue, Lists U N I T 5 P a g e | 25
LAB PROGRAMS FROM UNIT 5
LAB 15 (15.1 TO 15.3)
1) PROGRAM TO IMPLEMENT BINARY
SEARCH USING RECURSION
2) PROGRAM TO IMPLEMENT
EXCHANGE SORT
3) PROGRAM TO IMPLEMENT
SELECTION SORT
LAB 16 (16.1 TO 16.3)
1) PROGRAM TO IMPLEMENT STACK
USING ARRAYS
2) PROGRAM TO IMPLEMENT QUEUE
USING ARRAYS
3) PROGRAM TO IMPLEMENT LINKED
LIST WITH INSERTING & DELETION
OPERATIONS
top related