Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
1. Bubble sort
2. Selection sort
3. Quick sort
4. Insertion sort etc…
Step 4: Exit
3ST Technologies – Confidential C & DS 6
Example – Bubble Sort
Sort the list {15, 4, 23, 12, 56, 2} using bubble sort.
• The worst case for bubble sort occurs when the list is in reverse order. In
this case, every item will have to be swapped with every other item on
every pass through the algorithm. As in selection sort, there will be
O(N2) comparisons. The number of swaps in the worst case is greater
than in selection sort: each comparison results in a swap, so there are
O(N2) swaps in bubble sort!
• The average case looks like the worst case: O(N2) comparisons and O(N2)
swaps. The tradeoff is that we may be able to do half as many iterations,
on average, as we do in selection sort. From a mathematical standpoint,
however, bubble sort performs worse than selection sort in terms of the
number of swaps, and the same as selection sort in terms of the number
of comparisons.
3ST Technologies – Confidential C & DS 9
Example – Bubble Sort
#include <stdio.h>
main() {
int array[100], n, c, d, swap;
printf("Enter number of elements\n");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
for (c = 0 ; c < ( n - 1 ); c++) {
for (d = 0 ; d < n - c - 1; d++) {
if (array[d] > array[d+1]) { /* For decreasing order use < */
swap = array[d];
array[d] = array[d+1];
array[d+1] = swap;
}
}
}
printf("Sorted list in ascending order:\n");
for ( c = 0 ; c < n ; c++ )
printf("%d\n", array[c]);
}
3ST Technologies – Confidential C & DS 10
Selection Sort
• We put the smallest item at the start of the list, then the next smallest
item at the second position in the list, and so on until the list is in order.
Algorithm
for i=0 to N-2
{
smallest = list item at index i
for j=i+1 to N-1
{
if item at position j < smallest
smallest = list item at index j
}
swap current item with smallest item found
}
3ST Technologies – Confidential C & DS 11
Example – Selection Sort
Sort the list {15, 4, 23, 12, 56, 2} using selection sort.
1. Current item = 15, Smallest = 15
Compare 15 and 4 : 4 is smaller, so set smallest = 4
Compare 4 and 23 : 4 is smaller
Compare 4 and 12 : 4 is smaller
Compare 4 and 56 : 4 is smaller
Compare 4 and 2 : 2 is smaller, so set smallest = 2
End of list : swap 15 and 2
List is now {2, 4, 23, 12, 56, 15} and 2 is in its proper position.
2. Current item = 4, Smallest = 4
Compare 4 and 23 : 4 is smaller
Compare 4 and 12 : 4 is smaller
Compare 4 and 56 : 4 is smaller
Compare 4 and 15 : 4 is smaller
End of list : nothing to swap. List is same as in previous step and both 2 and 4
are in their proper positions.
3ST Technologies – Confidential C & DS 12
Example – Selection Sort Continue…
3. Current item = 23, Smallest = 23
Compare 23 and 12 : 12 is smaller, so set smallest = 12
Compare 12 and 56 : 12 is smaller
Compare 12 and 15 : 12 is smaller
End of list : swap 23 and 12
List is now {2, 4, 12, 23, 56, 15}.
4. Current item = 23, Smallest = 23
Compare 23 and 56 : 23 is smaller
Compare 23 and 15 : 15 is smaller, so set smallest = 15
End of list : swap 23 and 15
List is now {2, 4, 12, 15, 23, 56}
5. Current item = 23, Smallest = 23
Compare 23 and 56 : 23 is smaller
End of list : nothing to swap. List is same as in previous step.
Finished! Sorted list is {2, 4, 12, 15, 23, 56}.
3ST Technologies – Confidential C & DS 13
Performance of selection sort
• The best case for selection sort occurs when the list is already sorted. In this
case, the number of swaps is zero. We still have to compare each item in the
list to each other item in the list on each pass through the algorithm.
• The first time through, we compare the first item in the list to all other items
in the list, so the number of comparisons is (N-1).
• The second time through, we compare the second item in the list to the
remaining items in the list, so the number of comparisons is (N-2).
• The total number of comparisons is (N − 1) + (N − 2) + ... + 2 + 1. This equation
simplifies to N(N + 1)/2 − 1, which is approximately N2. Thus, even in the best
case, selection sort requires O(N2) comparisons.
• The worst case for selection sort occurs when the first item in the list is the
largest, and the rest of the list is in order. In this case, we perform one swap
on each pass through the algorithm, so the number of swaps is N. The
number of comparisons is the same as in the best case, O(N2).
• The average case requires the same number of comparisons, O(N2), and
roughly N/2 swaps. Thus, the number of swaps in the average case is O(N).
• In summary, we say that selection sort is O(N) in swaps and O(N2) in
comparisons.
3ST Technologies – Confidential C & DS 14
Example – Selection Sort
main() {
int array[100], n, c, d, position, swap;
printf("Enter number of elements\n");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for ( c = 0 ; c < n ; c++ )
scanf("%d", &array[c]);
for ( c = 0 ; c < ( n - 1 ) ; c++ ) {
position = c;
for ( d = c + 1 ; d < n ; d++ ) {
if ( array[position] > array[d] )
position = d;
}
if ( position != c ) {
swap = array[c];
array[c] = array[position];
array[position] = swap;
}
}
printf("Sorted list in ascending order:\n");
for ( c = 0 ; c < n ; c++ )
printf("%d\n", array[c]);
}
3ST Technologies – Confidential C & DS 15
Insertion Sort
It is simplest sorting algorithm which sort the array by shifting
elements one by one. Following are some important
characteristics of insertion sort
➢We do this by looking at the middle item in the list, and determining if our
search term is higher or lower than the middle item.
➢If it’s lower, we eliminate the upper half of the list and repeat our search
starting at the point halfway between the first item and the middle item.
➢If it’s higher, we eliminate the lower half of the list and repeat our search
starting at the point halfway between the middle item and the last item.
➢We repeat this until we either find the item in the list or we’ve ruled out
every possible place that the item could be if it were in the list.
• If there exists only one link field in each and every node in
the list, then linked list is called singly linked list.
struct node {
int info;
struct node *link;
};
typedef struct node *NODE;
temp 50
first 20 45 10 80
After inserting
50 20 45 10 80
temp 50 20 45 10 80
first 20 45 10 80
20 45 10 80 50
prev cur
first 20 45 10 80 50
• Function to delete a node from the rear end of the linked list
NODE delete_rear(NODE first) {
NODE cur, prev;
if(first == NULL) {
printf(“List is empty cannot delete\n”);
return first;
}
if(first->link == NULL) {
printf(“The item to deleted is %d\n”,first->info);
freenode(first);
first = NULL;
return first;
}
3ST Technologies – Confidential C & DS 39
Singly Linked Lists
• Function to delete a node from the rear end of the linked list cont…
prev=NULL;
cur = first;
while(cur->link !=NULL) {
prev=cur;
cur=cur->link;
}
printf(“The item deleted is %d\n”, cur->info);
freenode(cur);
prev->link = NULL:
return first;
}
first=first->link
prev cur
10 20 30 40
prev->link=cur->link
• Function to delete a node at a specified position in the linked list
NODE delete_pos(int pos, NODE first) {
NODE cur;
NODE prev;
int count;
if(first == NULL) {
printf(“List is empty\n”);
return NULL;
}
head
count
head 4 45 10 80 50
35
temp
first 10 20 30 35 40
if(pos == 1) {
temp->link;
return temp;
}
count=1;
prev = NULL;
cur=first;
while(cur != NULL && count !=pos) {
prev = cur;
cur = cur->link;
count++;
}
if(count == pos) {
prev->link = temp;
temp->link = cur;
return first;
}
printf(“Invalid position specified\n”);
return first;
}
3ST Technologies – Confidential C & DS 45
Linked Lists
• Linked list vs. arrays
• Linked list
• Advantage
➢ Constant-time insertion/removal once the insertion/removal
point is known
➢ Allocate nodes dynamically as needed, does not get full.
• Disadvantage
➢ No direct access to elements
➢ Extra storage for links
• Arrays
• Advantage
➢ Direct access to elements (by indexing)
• Disadvantage
➢ Linear time insertion/removal due to shifting
➢ Size is fixed
3ST Technologies – Confidential C & DS 46
Linked Lists
• Limitation of singly linked lists
20 45 10 80
temp last
50 20 45 10 80
• Function to insert a node at the front end in the circular linked list
NODE insert_front(int item, NODE last) {
NODE temp;
temp = getnode();
temp->info = item;
if(last == NULL)
last=temp;
else
temp->link = temp;
return last;
}
3ST Technologies – Confidential C & DS 49
Circular Linked Lists
• Insert a node at the rear end in the circular linked list last
50 20 45 10
last temp
50 20 45 10 80
last
50 20 45 10 80
• Function to insert a node at the rear end in the circular linked list
NODE insert_rear(int item, NODE last) {
NODE temp;
temp = getnode();
temp->info = item;
if(last == NULL)
last=temp;
else {
temp->link = last->link; last->link=temp; }
return temp;
}
3ST Technologies – Confidential C & DS 50
Circular Linked Lists
• Deleting a node from the front end in the circular linked list
first last
50 20 45 10 80
• Function to delete a node from the front end in the circular linked list
NODE delete_front(NODE last) {
NODE temp, first;
if(last == NULL) {
printf(“List is empty\n”);
return NULL;
}
if(last->link == last) {
printf(“The item deleted is %d\n”, last->info);
freenode(last);
return NULL;
}
first= last->link;
last->link = first->link;
printf(“The item deleted is %d\n”, first->info);
freenode(first);
return last;
}
3ST Technologies – Confidential C & DS 51
Circular Linked Lists last
• Deleting a node from the rear end in the circular linked list
prev
50 20 45 10 80
• Function to delete a node from the rear end in the circular linked list
NODE delete_rear(NODE last) {
NODE prev;
if(last == NULL) {
printf(“List is empty\n”); return NULL;
}
if(last->link == last) {
printf(“The item deleted is %d\n”, last->info);
freenode(last); return NULL;
}
prev= last->link;
while(prev->link != last)
prev=prev->link;
last->link = first->link;
printf(“The item deleted is %d\n”, first->info);
freenode(last);
return prev;
}
3ST Technologies – Confidential C & DS 52
Circular Linked Lists
• Function to display the contents of a circular linked list
void display(NODE last) {
NODE temp;
if(last == NULL) {
printf(“List is empty\n”);
return;
}
printf(“Contents of the list is \n”);
for(temp=last->link; temp != last; temp=temp->link) {
printf(“%d “, temp->info);
printf(“\n”);
}
}
temp 50
• Function to insert a node at the specified position node in the circular linked list
insert_position(int item, int pos, NODE head) {
NODE prev, cur, temp;
int i;
if(pos > head->info+1) || (pos<1) {
printf(“Invalid position\n”);
return head;
}
prev=head;
cur=head->link;
for(i=1;i<pos;i++) {
prev=cur; cur=cur->link;
}
temp=getnode(); temp->info=item; prev->link=temp; temp->link=cur; head->info +=1;
return head;
}
3ST Technologies – Confidential C & DS 55
Circular Linked Lists
• Delete a node at the specified position node in the circular linked list
prev cur
head 4 20 45 10 80
• Function to delete a node at the specified position node in the circular linked list
NODE delete_position(int pos, NODE head) {
NODE prev, cur;
int i;
if(head->link == head) {
printf(“List is empty\n”); return head;
}
if(pos > head->info+1) || (pos<1) {
printf(“Invalid position\n”); return head;
}
prev = cur = head;
for(i=1;i<pos;i++) {
prev=cur; cur=cur->link;
}
prev->link = cur->link; freenode(cur);
head->info -=1; return head;
}
3ST Technologies – Confidential C & DS 56
Doubly Linked Lists
• Disadvantages of linked lists
1. Using singly linked lists and circular linked list it is not possible to
traverse the list backwards
2. To find predecessor, it is required to traverse the list from the
first node in case of singly linked list. In case of circular list, the
predecessor can be obtained by traversing the whole list from
the node specified.
• Doubly linked lists
• Here it is possible to traverse the list in forward and backward
direction
• It has two link fields
• The link field which contains the address of the left node is called
left link (llink)
• The link field which contains the address of the right node is
called right link (rlink)
3ST Technologies – Confidential C & DS 57
first
Doubly Linked Lists last
10 30
20 5
Doubly Linked List
first 20 10 30 5
head 10 30 5
head
header node
3ST Technologies – Confidential C & DS 58
Doubly Linked Lists
• Insert a node at the front end of the doubly linked list
cur
head 10 30 5
50 temp
• Function to insert a node at the front end of the doubly linked list
NODE insert_ front(int item, NODE head) {
NODE temp, cur;
temp = getnode();
temp->info = item;
cur = head->rlink;
head->rlink = temp;
temp->llink = head;
temp->rlink = cur;
cur->llink = temp;
return head;
}
3ST Technologies – Confidential C & DS 59
Doubly Linked Lists
• Insert a node at the rear end of the doubly linked list
head
10 30 5 50
temp
• Function to insert a node at the rear end of the doubly linked list
NODE insert_ rear(int item, NODE head) {
NODE temp, cur;
temp = getnode();
temp->info = item;
cur = head->llink;
head->llink = temp;
temp->rlink = head;
temp->llink = cur;
cur->rlink = temp;
return head;
}
3ST Technologies – Confidential C & DS 60
Doubly Linked Lists
• Delete a node at the front end of the doubly linked list
cur next
head
10 30 5
• Function to delete a node at the front end of the doubly linked list
NODE delete_ front(NODE head) {
NODE next, cur;
if(head->rlink == head) {
printf(“Deque is empty\n”);
return head;
}
cur = head->rlink;
next=cur->rlink;
head->rlink = next;
next->llink = head;
printf(“The node to be deleted is %d\n”, cur->info);
freenode(cur);
return head;
}
3ST Technologies – Confidential C & DS 61
Doubly Linked Lists
• Delete a node at the rear end of the doubly linked list
head
20 10 30 5
prev cur
• Function to delete a node at the rear end of the doubly linked list
NODE delete_ rear(NODE head) {
NODE prev, cur;
if(head->llink == head) {
printf(“Deque is empty\n”);
return head;
}
cur = head->llink;
prev=cur->llink;
head->llink = prev;
prev->rlink = head;
printf(“The node to be deleted is %d\n”, cur->info);
freenode(cur);
return head;
}
3ST Technologies – Confidential C & DS 62
Doubly Linked Lists
• Function to insert a node to the right of a specified node of a doubly linked list
NODE insert_right(int item, NODE head) {
NODE temp, cur, next;
if(head->rlink == head) {
printf(“List is empty\n”);
return head;
}
cur=head->rlink;
while(cur != head&& item !=cur->info)
cur=cur->rlink;
if(cur==head) {
printf(Key not found\n”);
return head;
}
next= cur->rlink;
printf(“Enter the item inserted towards right of %d=“, item);
temp = getnode();
scanf(“%d”, &temp->info);
cur->rlink= temp;
temp->llink=cur;
next->llink=temp;
temp->rlink=next;
return head;
}
3ST Technologies – Confidential C & DS 63
Doubly Linked Lists
• Function to insert a node to the left of a specified node of a doubly
linked list
NODE insert_left(int item, NODE head) {
NODE temp, cur, prev;
if(head->rlink == head) {
printf(“List is empty\n”);
return head;
}
cur=head->rlink;
while(cur != head && item != cur->info)
cur=cur->rlink;
if(cur==head) {
printf(Key not found\n”);
return head;
}
prev= cur->llink;
printf(“Enter the item inserted towards left of %d=“, item);
temp = getnode();
scanf(“%d”, &temp->info);
prev->rlink= temp;
temp->llink=cur;
cur->llink=temp;
temp->rlink=next;
return head;
}
3ST Technologies – Confidential C & DS 64
Stack
• Take the example of a cafeteria. The plates are placed one above the
other and every new plate is added at the top. When a plate is required,
it is taken off from the top and is used. We can call this process as
stacking of plates. Stack is therefore an ordered list of similar data type
• A stack is defined as a special type of data structure where items are
inserted from one end called top of stack.
• Here, the last item inserted will be on the top of the stack. Since
deletion is done from the same end, last item inserted is the first item
to be deleted out from the stack. i.e. stack is also called Last In First Out
(LIFO).
• push() function is used to insert an element into the stack and pop() is
used to delete an element from the stack.
• Both insertion and deletion are allowed at only one end of stack.
• Stack is said to be in overflow state when it is completely full and it is
said to be underflow state when it is completely empty.
• Initially the stack is empty. At that time top points to bottom of stack.
• Finally when all items are deleted, top points to bottom of the stack.
• When the stack is empty, it is not possible to delete any item and this
situation is called underflow of stack.
3ST Technologies – Confidential C & DS 68
Stack : Static implementation
#include <stdio.h>
#define MAXSIZE 5
struct stack
{
int stk[MAXSIZE];
int top;
};
void push(void);
void pop(void);
void display(void);
Substituting T5
T4 F + T3 E^ F +
A T2 + E ^ F +
A T1 D * + E ^ F +
ABC–D*+E^F+
r f 2 3
0 1 2 3 4
• Circular Queue 10
f 4
r 1
10
0
• Priority Queue
f, r
3ST Technologies – Confidential C & DS 84
Queues – Example
#include <stdio.h> switch (choice) {
#define MAX 50 case 1:
int queue_array[MAX]; Enqueue();
int rear = - 1, front = - 1; break;case 2:
void Enqueue(); Dequeue();
void Dequeue(); break;
void display();
case 3:
main() {
int choice; display();
while (1) { break;
printf("1. Insert element to queue \n"); case 4:
printf("2. Delete element from queue \n"); break;
printf("3. Display all elements of queue \n"); default:
printf("4. Quit \n"); printf("Wrong choice \n");
printf("\n"); } /*End of switch*/
printf("Enter your choice : "); } /*End of while*/
scanf("%d", &choice);
} /*End of main()*/
f r
After inserting 50
10 20 30 40 50
f r
• Function to check whether the queue is full
int qfull (int r) {
return (r == QUEUE_SIZE-1)?1:0;
}
• Function to check for underflow of queue
int qempty(int f,int r) {
return(f>r)?1:0;
}
3ST Technologies – Confidential C & DS 88
Queues – Example – Continue….
10 20 30 40
f r
20 30 40
f r
50
f,r
• Function to display the contents of queue
void display(int q[ ],int f,int r) {
int i;
if(qempty(f, r)) {
printf(“Queue is empty\n”);
return;
}
printf(“Contents of queue is\n”);
for(i=f;i<=r;i++)
printf(“%d\n”, q[i]);
}
3ST Technologies – Confidential C & DS 89
Queues – Example – Continue….
• Function to insert an item at the rear end of queue
void insert_rear(int item.int q[ ], int *r)v{
if(qfull(*r)) {
printf(“Queue overflow\n”);
return;
}
q[++(*r)]=item;
}
• Function to delete an item from the front end
void delete_front(int q[ ], int *f, int *r) {
if(qempty(*f, *r)) {
printf(“Queue underflow\n”);
return;
}
printf(“The element deleted is %d\n”, q[(*f)++]);
if(*f > *r) {
*f = 0;
*r = -1;
}
}
3ST Technologies – Confidential C & DS 90
Queues
• Disadvantages queue
• Consider the queue, when 5 elements say 10, 20, 30, 40 and 50 are
inserted and then deleting first four items 10, 20, 30 and 40. If we try to
insert an element say 60, since r has the value QUEUE_SIZE-1, we get an
overflow condition and it is not possible to insert any element. Even
though queue is not full, in this case, it is not possible to insert any item
into the queue. 0 1 2 3 4
50
f, r
0 1 2 3 4
if (f==0 && r==-1)
q[++r]=item;
r f
0 1 2 3 4
30 40 if (f!=0)
q[--f]=item;
f r
0 1 2 3 4
10 20 30 40 Not possible to insert an
item at the front end
f r
f
r f r After inserting 20 and 30
3 2
3 2 r
30
4 1
10 4 20 1
0 10
0
f, r f
0 1 2 3 4 0 1 2 3 4
10 20 30 40 50 30 40 50
f r
f r
After inserting 40 & 50 After deleting 40 & 50
3
3
40 2 40 2 f
30 30
50 r 4 50
r 4
20 1
10 1
0
f 0
r f
f
2
• Function to check queue overflow 3
30
40
int qfull (int count) {
return (count == QUEUE_SIZE) ? 1:0; 4 50 1
} 60
0
r
• Function to check queue underflow
int qempty(int count) {
return (count == 0)?1:0;
}
• If the elements in the queue are of same priority, then the element,
which is inserted first into queue, is processed