Data Structure in C (Lab. Programs) Programs are complete in best of my knowledge with zero compilation error in IDE Bloodshed Dev-C++. These can be easily portable to any versions of Visual Studio or Qt. If you need any guidance please let me know via comments and Always Enjoy Programming. 2013 Saket Kr. Pathak Software Developer 3D Graphics
Programs are complete in best of my knowledge with zero compilation error in IDE Bloodshed Dev-C++. These can be easily portable to any versions of Visual Studio or Qt. If you need any guidance please let me know via comments and Always Enjoy Programming.
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Data Structure in C (Lab. Programs)Programs are complete in best of my knowledge with zero compilation error in IDE Bloodshed Dev-C++. These can be easily portable to any versions of Visual Studio or Qt. If you need any guidance please let me know via comments and Always Enjoy Programming.
2013
Saket Kr. Pathak Software Developer 3D Graphics
Data Structure in C (Lab. Programs)
Content (Programs List)
S. No. Subject Date Sign Remark1. WAP in C for following Sorting Methods
2. WAP in C for following Searching Methods Linear Search Binary Search
3. WAP in C for array implementation of Stack Queue Circular Queue Linked List
4. WAP in C using dynamic memory allocation of Stack Queue Circular Queue Linked List
5. WAP in C for implementation of Binary Tree.
6. WAP in C for Tree Traversal Pre-Order In-Order Post-Order
7. WAP in C for Graph Traversal Breadth First Search Depth First Search
8. WAP in C for Minimum Cost Spanning Tree
9. WAP in C for Shortest Path Problem
Saket Kr. Pathak Page 2
Data Structure in C (Lab. Programs)
1. WAP in C for following Sorting Methods Bubble Sort Merge Sort Insertion Sort Selection Sort Quick Sort
Program:Bubble Sort:
Algorithm –
[1]Compare each pair of adjacent elements from the beginning of an array and, if they are in reversed order, swap them.
[2]If at least one swap has been done, repeat step 1.
Time Complexity –
Best case: O (n) timeAverage case: O (n2) timeWorst case: O (n2) time
Code – Snippet:
#include <stdio.h>
int* bubble_sort(int i_store[], int i_size);int* get_elem(int i_size);void disp_elem(int i_store[], int i_size);
int main(){ printf("\n\n\n"); printf("\t\t\tWAP of Bubble sort."); printf("\n\n\n"); int i_store_size; printf("Enter the total number of items to store: "); scanf("%d", &i_store_size); int* ip_store = get_elem(i_store_size); ip_store = bubble_sort(ip_store, i_store_size);
[1]If the input sequence has fewer than two elements, return.[2]Partition the input sequence into two halves.[3]Sort the two subsequences using the same algorithm.[4]Merge the two sorted subsequences to form the output
sequence.
Time Complexity –
Best case: O (n * log (n)) timeAverage case: O (n * log (n)) timeWorst case: O (n * log (n)) time
void conquer_(int* ip_storage, int i_low, int i_mid, int i_high){ int* ip_temp_store_1 = malloc(sizeof(int) * ARRAY_SIZE); int* ip_temp_store_2 = malloc(sizeof(int) * ARRAY_SIZE); int n1,n2,i,j,k; n1 = i_mid - i_low + 1; n2 = i_high - i_mid;
printf("\n\tMerge low(%d) | mid(%d) | high(%d): ", i_low, i_mid, i_high); printf("\n\tip_temp_store_1: "); for(i=0; i<n1; i++) { ip_temp_store_1[i] = ip_storage[i_low+i]; printf("%d", i, ip_temp_store_1[i]); } printf("\n\tip_temp_store_2: "); for(j=0; j<n2; j++) { ip_temp_store_2[j] = ip_storage[i_mid+j+1]; printf("%d", j, ip_temp_store_2[j]); } // To mark the end of each temporary array ip_temp_store_1[i] = 10000000; ip_temp_store_2[j] = 10000000; combine_(ip_storage, ip_temp_store_1, ip_temp_store_2, i_low, i_high);}
void combine_(int* storage, int* temp_arr_1, int* temp_arr_2, int i_low, int i_height){ int i=0; int j=0; int k; printf("\nResult: "); for (k=i_low; k<=i_height; k++) { if (temp_arr_1[i] <= temp_arr_2[j]) storage[k] = temp_arr_1[i++]; else storage[k]=temp_arr_2[j++];
[1]Start with the result as the first element of the input.[2]Loop over the input until it is empty, "removing" the first
remaining (leftmost) element.[3]Compare the removed element against the current result,
starting from the highest (rightmost) element, and working left towards the lowest element.
[4]If the removed input element is lower than the current result element, copy that value into the following element to make room for the new element below, and repeat with the next lowest result element.
[5]Otherwise, the new element is in the correct location; save it in the cell left by copying the last examined result up, and start again from (2) with the next input element.
Time Complexity –
Best case: O (n) timeAverage case: O (n2) timeWorst case: O (n2) time
Code – Snippet:
#include <stdio.h>
int* insertion_sort(int i_store[], int i_size);int* get_elem(int i_size);void disp_elem(int i_store[], int i_size);
int main(){ printf("\n\n\n"); printf("\t\t\tWAP of Insertion sort."); printf("\n\n\n"); int i_store_size; printf("Enter the total number of items to store: "); scanf("%d", &i_store_size); int* ip_store = get_elem(i_store_size); ip_store = insertion_sort(ip_store, i_store_size); disp_elem(ip_store, i_store_size); printf("\n\n\n"); system("pause"); return 0;}
Saket Kr. Pathak Page 9
Data Structure in C (Lab. Programs)
int* get_elem(int i_size){ int* ip_store = malloc(sizeof(int) * i_size); int i_count = 0; while (i_size) { printf("\nEnter item for index - %d : ", i_count); scanf("%d", (ip_store+i_count)); i_count++; i_size--; } return ip_store;}
int* insertion_sort(int i_store[], int i_size){ int i_temp; int i_count_0, i_count_1, i_count_2; for (i_count_0 = 1; i_count_0 <= (i_size-1); ++i_count_0) { for (i_count_1 = 0; i_count_1 < i_count_0; ++i_count_1)
[1]Get a hand of unsorted cards/numbers.[2]Set a marker for the sorted section after the first card of the
hand.[3]Repeat steps 4 through 6 until the unsorted section is empty.[4]Select the first unsorted card.[5]Swap this card to the left until it arrives at the correct sorted
position.[6]Advance the marker to the right one card.[7]Stop
Time Complexity –
Best case: O (n2) timeAverage case: O (n2) timeWorst case: O (n2) time
Code – Snippet:
#include <stdio.h>
int* selection_sort(int i_store[], int i_size);int* get_elem(int i_size);void disp_elem(int i_store[], int i_size);
int main(){ printf("\n\n\n"); printf("\t\t\tWAP of Selection sort."); printf("\n\n\n"); int i_store_size; printf("Enter the total number of items to store: "); scanf("%d", &i_store_size);
[1]Choosing the pivot.[2]Partitioning.[3]Recursively quick-sort the left and the right parts.
Time Complexity –
Best case: O (n * log (n)) timeAverage case: O (n * log (n)) timeWorst case: O (n2) time
Code – Snippet:
#include <stdio.h>
int* quick_sort(int i_store[], int i_start, int i_end);int* get_elem(int i_size);void disp_elem(int i_store[], int i_size);
int main(){ printf("\n\n\n"); printf("\t\t\tWAP of Quick sort."); printf("\n\n\n"); int i_store_size; printf("Enter the total number of items to store: "); scanf("%d", &i_store_size);
void disp_elem(int i_store[], int i_size){ printf("\nDisplaying Elements of store: "); int i_ndx = 0; while (i_size) { printf("%d", i_store[i_ndx]); i_ndx++; i_size--; }}
void linear_search(int* i_storage, int i_srch_item, int i_num_item){ int i_count; bool b_flag = false; for (i_count = 0; i_count < i_num_item; ++i_count) { if (i_storage[i_count] == i_srch_item) { b_flag = true; printf("Item (%d) is found at position: %d", i_srch_item, i_count); break;
Saket Kr. Pathak Page 16
Data Structure in C (Lab. Programs)
} } if (!b_flag) printf("Item not found.");}
void get_input(int* i_storage, int i_num_item){
printf("Your Storage Items are: \n\t");
int i_loop_count;for(i_loop_count = 0; i_loop_count < i_num_item; +
+i_loop_count){
printf("%d, ", i_storage[i_loop_count]);}
printf("\n\n\n");
int i_srch_item;printf("Please Enter the item (number) to search: ");scanf("%d", &i_srch_item);
printf("\n\tTo Push Item into Stack.");int i_item = 0;printf("\n\tPlease Enter the item: ");scanf("%d", &i_item);int i_check = push_item(i_item);if(i_check == 1)
return 1;else
return 0;break;
}case 2:{
printf("\n\tTo Pop Item from Stack.");int i_item = 0;printf("\n\tPlease Enter the item: ");scanf("%d", &i_item);int i_check = pop_item(i_item);if(i_check == 1)
return 1;else
return 0;break;
}
Saket Kr. Pathak Page 23
Data Structure in C (Lab. Programs)
case 3:{
printf("\n\tTo Display Item of Stack.");int i_check = disp_item();if(i_check == 1)
printf("\n\tTo Push Item into Queue.");int i_item = 0;printf("\n\tPlease Enter the item: ");scanf("%d", &i_item);int i_check = push_item(i_item);if(i_check == 1)
return 1;else
return 0;break;
}case 2:{
printf("\n\tTo Pop Item from Queue.");int i_item = 0;printf("\n\tPlease Enter the item: ");scanf("%d", &i_item);int i_check = pop_item(i_item);if(i_check == 1)
return 1;else
Saket Kr. Pathak Page 28
Data Structure in C (Lab. Programs)
return 0;break;
}case 3:{
printf("\n\tTo Display Item of Queue.");int i_check = disp_item();if(i_check == 1)
printf("\n\tTo Push Item into Queue.");int i_item = 0;printf("\n\tPlease Enter the item: ");scanf("%d", &i_item);int i_check = push_item(i_item);if(i_check == 1)
return 1;else
return 0;break;
}case 2:{
printf("\n\tTo Pop Item from Queue.");int i_item = 0;printf("\n\tPlease Enter the item: ");scanf("%d", &i_item);int i_check = pop_item(i_item);if(i_check == 1)
return 1;else
return 0;break;
}case 3:{
printf("\n\tTo Display Item of Queue.");int i_check = disp_item();if(i_check == 1)
int i_item = 0;int i_indx = 0;printf("\n\tPlease Enter the item: ");scanf("%d", &i_item);printf("\n\tPlease Enter the index: ");scanf("%d", &i_indx);int i_check = push_node(i_item, i_indx);if(i_check == 1)
return 1;else
return 0;break;
}case 2:{
printf("\n\tTo Pop Item from Queue.");int i_check = del_option();{
if (i_check == 0) printf("\n\n\n\tInvalid input.");
else ; } i_check = pop_node(i_check);
if(i_check == 1)return 1;
elsereturn 0;
break;}case 3:{
printf("\n\tTo Display Item of Queue.");int i_check = disp_node();if(i_check == 1)
return 1;else
return 0;break;
}case 4:{
printf("\n\tTo Exit.");return 0;break;
}default:
Saket Kr. Pathak Page 36
Data Structure in C (Lab. Programs)
{return 0;break;
}}
}
int del_option(void){ printf("\n\t\t---------------------------"); {
printf("\n\tTo Push Item into Stack.");int i_item = 0;printf("\n\tPlease Enter the item: ");scanf("%d", &i_item);int i_check = push_item(i_item);if(i_check == 1)
return 1;else
return 0;break;
}case 2:{
printf("\n\tTo Pop Item from Stack.");int i_item = 0;printf("\n\tPlease Enter the item: ");scanf("%d", &i_item);int i_check = pop_item(i_item);if(i_check == 1)
return 1;else
return 0;break;
}case 3:{
printf("\n\tTo Display Item of Stack.");int i_check = disp_item();if(i_check == 1)
return 1;else
return 0;break;
}case 4:{
printf("\n\tTo Exit.");return 0;break;
}default:
Saket Kr. Pathak Page 50
Data Structure in C (Lab. Programs)
{return 0;break;
}}
}
int push_item(int i_item){
if(i_top == (STACK_SIZE - 1)){
printf("\n\tStack Overflow.");return 0;
}else{
*(stack + (++i_top)) = i_item;printf("\n\tItem - %d, has successfully pushed into
printf("\n\tTo Push Item into Queue.");int i_item = 0;printf("\n\tPlease Enter the item: ");scanf("%d", &i_item);int i_check = push_item(i_item);if(i_check == 1)
return 1;else
return 0;
Saket Kr. Pathak Page 55
Data Structure in C (Lab. Programs)
break;}case 2:{
printf("\n\tTo Pop Item from Queue.");int i_item = 0;printf("\n\tPlease Enter the item: ");scanf("%d", &i_item);int i_check = pop_item(i_item);if(i_check == 1)
return 1;else
return 0;break;
}case 3:{
printf("\n\tTo Display Item of Queue.");int i_check = disp_item();if(i_check == 1)
printf("\n\tTo Push Item into Queue.");int i_item = 0;printf("\n\tPlease Enter the item: ");scanf("%d", &i_item);int i_check = push_item(i_item);if(i_check == 1)
return 1;else
return 0;break;
}case 2:{
printf("\n\tTo Pop Item from Queue.");int i_item = 0;printf("\n\tPlease Enter the item: ");scanf("%d", &i_item);int i_check = pop_item(i_item);if(i_check == 1)
return 1;else
return 0;break;
}case 3:{
printf("\n\tTo Display Item of Queue.");int i_check = disp_item();if(i_check == 1)
int i_item = 0;int i_indx = 0;printf("\n\tPlease Enter the item: ");scanf("%d", &i_item);printf("\n\tPlease Enter the index: ");scanf("%d", &i_indx);int i_check = push_node(i_item, i_indx);if(i_check == 1)
return 1;else
return 0;break;
}case 2:{
printf("\n\tTo Pop Item from Queue.");int i_check = del_option();{
if (i_check == 0) printf("\n\n\n\tInvalid input.");
else ; } i_check = pop_node(i_check);
if(i_check == 1)return 1;
elsereturn 0;
break;}case 3:{
printf("\n\tTo Display Item of Queue.");int i_check = disp_node();if(i_check == 1)
return 1;else
return 0;break;
}case 4:{
printf("\n\tTo Exit.");return 0;break;
}default:
Saket Kr. Pathak Page 70
Data Structure in C (Lab. Programs)
{return 0;break;
}}
}
int del_option(void){ printf("\n\t\t---------------------------"); {
//If ITEM is less that the ITEM in Root Node //Traverse the node in LEFT - SIDE.if(nw_node->i_data < (*root)->i_data)
insert_node(&(*root)->left_node, nw_node);//If ITEM is greater that the ITEM in Root Node //Traverse the node in RIGHT - SIDE.else if(nw_node->i_data > (*root)->i_data)
insert_node(&(*root)->right_node, nw_node);
return false;}
}
void disp_tree(struct node *root){
//Check for NULL in LEFT - Nodeif(root->left_node)
struct node *temp_node = (struct node*)malloc(sizeof(struct node*)); temp_node = NULL; struct node *del_node = (struct node*)malloc(sizeof(struct node*)); del_node = NULL; while (current_node != NULL) { if (current_node->i_data > i_data) { parent_node = current_node; current_node = current_node->left_node; } else if (current_node->i_data < i_data) { parent_node = current_node; current_node = current_node->right_node; } else if (i_data == current_node->i_data) { del_node = current_node; //Node to delete is Leaf-Node if ((del_node->left_node == NULL) && (del_node->right_node == NULL)) { //If the node to delete is on the left-side if (parent_node->left_node == del_node) { printf("\n\tNode deleting with value (%d), left of the parent.", del_node->i_data); parent_node->left_node = NULL; free(del_node); break; } //If the node to delete is on the right-side else if (parent_node->right_node == del_node) { printf("\n\tNode deleting with value (%d), right of the parent.", del_node->i_data); parent_node->right_node = NULL; free(del_node); break; } } //Node to delete has one child
Saket Kr. Pathak Page 78
Data Structure in C (Lab. Programs)
else if ((del_node->left_node == NULL) || (del_node->right_node == NULL)) { //If the node to delete is on the left-side if (parent_node->left_node == del_node) { if (del_node->left_node != NULL) { printf("\n\tNode deleting with value (%d), left of the parent.", del_node->i_data); parent_node->left_node = del_node->left_node; free(del_node); break; } else if (del_node->right_node != NULL) { printf("\n\tNode deleting with value (%d), left of the parent.", del_node->i_data); parent_node->left_node = del_node->right_node; free(del_node); break; } } else if (parent_node->right_node == del_node) { if (del_node->left_node != NULL) { printf("\n\tNode deleting with value (%d), right of the parent.", del_node->i_data); parent_node->right_node = del_node->left_node; free(del_node); } else if (del_node->right_node != NULL) { printf("\n\tNode deleting with value (%d), right of the parent.", del_node->i_data); parent_node->right_node = del_node->right_node; free(del_node); } } } //Node to delete has two child
Saket Kr. Pathak Page 79
Data Structure in C (Lab. Programs)
else if ((del_node->left_node != NULL) && (del_node->right_node != NULL)) {
printf("\n\tNode to delete has two children\n");
temp_node = del_node; //If the node to delete is Root if (parent_node == NULL)
int main(){ printf("\n\n\n"); printf("\t\t\tWAP for implementation of Binary Tree.."); printf("\n\n\n"); int i_tree_elem; printf("Enter the total number of elements: "); scanf("%d", &i_tree_elem); struct node *root = (struct node*)malloc(sizeof(struct node)); root = get_tree_element(i_tree_elem); printf("\n\n\n"); printf("\tWAP of Selection sort.\n"); disp_tree(root); int i_choice = disp_menu(); traverse_tree(i_choice, root); printf("\n\n\n"); system("pause"); return 0;}
//If ITEM is less that the ITEM in Root Node //Traverse the node in LEFT - SIDE.if(nw_node->i_data < (*root)->i_data)
insert_node(&(*root)->left_node, nw_node);//If ITEM is greater that the ITEM in Root Node //Traverse the node in RIGHT - SIDE.else if(nw_node->i_data > (*root)->i_data)
insert_node(&(*root)->right_node, nw_node);
return false;}
}
void disp_tree(struct node *root){
//Check for NULL in LEFT - Nodeif(root->left_node)
7. WAP in C for Graph Traversal Breadth First Search Depth First Search
Program:
Breadth First Search:
Algorithm –
[1]Enqueue the root node.[2]Dequeue a node and examine it
a. If the element sought is found in this node, quit the search and return a result.
b. Otherwise enqueue any successors (the direct child nodes) that have not yet been discovered.
[3]If the queue is empty, every node on the graph has been examined – quit the search and return "not found".
[4]If the queue is not empty, repeat from Step 2
Time Complexity –
Saket Kr. Pathak Page 87
Data Structure in C (Lab. Programs)
The total time for initializing is O (n) and the total time for the queuing operations is O (n) because each node is put on the queue exactly once. The total time in the main loop is O (e) because we look at each edge at most twice, once from each direction. This gives a time complexity of O (n + e).
int main(){ printf("\n\n\n"); printf("\t\t\tWAP for Graph Traversal (Depth First Search)."); printf("\n\n\n"); bool b_check; b_check = get_graph_input(); if (b_check) b_check = initialize_nodes(); printf("\n\n\n"); printf("Depth First Path within the given graph:\n"); breadth_first_search(); printf("\n\n\n"); system("pause"); return 0;}
bool get_graph_input(void){
Saket Kr. Pathak Page 88
Data Structure in C (Lab. Programs)
printf("Enter Number of Nodes: "); scanf("%d", &i_no_nodes); i_adjacency_matrix = malloc(sizeof(int) * i_no_nodes); i_nodes_visit = malloc(sizeof(int) * i_no_nodes); i_bfs_path = malloc(sizeof(int) * i_no_nodes); int i_temp = 0; int i_count, j_count; for (i_count = 0; i_count < i_no_nodes; ++i_count) { *(i_adjacency_matrix + i_count) = (int*)malloc(sizeof(int) * i_no_nodes); for (j_count = 0; j_count < i_no_nodes; ++j_count) { printf("\nConection of node %d to node %d is: ", i_count, j_count); scanf("%d", &i_temp); if ((i_temp == 1)||(i_temp == 0)) i_adjacency_matrix[i_count][j_count] = i_temp; else { printf("Input is invalid."); return false; } } } printf("\n\n\nAdjacency Matrix, so formed:"); for (i_count = 0; i_count < i_no_nodes; ++i_count) { printf("\n"); for (j_count = 0; j_count < i_no_nodes; ++j_count) printf("\t%d", i_adjacency_matrix[i_count][j_count]); } return true;}
bool initialize_nodes(void){ int i_count; for (i_count = 0; i_count < i_no_nodes; ++i_count) i_nodes_visit[i_count] = 0; return true;
Saket Kr. Pathak Page 89
Data Structure in C (Lab. Programs)
}
void breadth_first_search(void){ int i_count; int i_start_node; printf("\n\tPlease Enter Starting Node: "); scanf("%d", &i_start_node); check_node(i_start_node); for (i_count = 1; i_count <= i_no_nodes; ++i_count) if (i_nodes_visit[i_count]) printf("%d\t",i_count); else printf("\n Bfs is not possible");}
void check_node(int i_start_node){ int i_count; for (i_count = 0; i_count <= i_no_nodes; ++i_count) if ((i_adjacency_matrix[i_start_node][i_count]) && (!i_nodes_visit[i_count])) i_bfs_path[++n_flag] = i_count; if (flag <= n_flag) { i_nodes_visit[i_bfs_path[flag]] = 1; check_node(i_bfs_path[flag++]); }
[1]If the initial state is a goal state, quit and return success.
Saket Kr. Pathak Page 90
Data Structure in C (Lab. Programs)
[2]Otherwise, loop until success or failure is signaled. Generate a state, say E, and let it be the successor of the
initial state. If there is no successor, signal failure. Call Depth-First Search with E as the initial state. If success is returned, signal success. Otherwise continue
int main(){ printf("\n\n\n"); printf("\t\t\tWAP for Graph Traversal (Depth First Search)."); printf("\n\n\n"); bool b_check; b_check = get_graph_input(); if (b_check) b_check = initialize_nodes(); printf("\n\n\n"); printf("Depth First Path within the given graph:\n"); depth_first_search(); printf("\n\n\n"); system("pause");
Saket Kr. Pathak Page 91
Data Structure in C (Lab. Programs)
return 0;}
bool get_graph_input(void){ printf("Enter Number of Nodes: "); scanf("%d", &i_no_nodes); i_adjacency_matrix = malloc(sizeof(int) * i_no_nodes); i_nodes_visit = malloc(sizeof(int) * i_no_nodes); int i_temp = 0; int i_count, j_count; for (i_count = 0; i_count < i_no_nodes; ++i_count) { *(i_adjacency_matrix + i_count) = (int*)malloc(sizeof(int) * i_no_nodes); for (j_count = 0; j_count < i_no_nodes; ++j_count) { printf("\nConection of node %d to node %d is: ", i_count, j_count); scanf("%d", &i_temp); if ((i_temp == 1)||(i_temp == 0)) i_adjacency_matrix[i_count][j_count] = i_temp; else { printf("Input is invalid."); return false; } } } printf("\n\n\nAdjacency Matrix, so formed:"); for (i_count = 0; i_count < i_no_nodes; ++i_count) { printf("\n"); for (j_count = 0; j_count < i_no_nodes; ++j_count) printf("\t%d", i_adjacency_matrix[i_count][j_count]); } return true;}
[1]Assign to every node a tentative distance value: set it to zero for our initial node and to infinity for all other nodes.
[2]Mark all nodes unvisited. Set the initial node as current. Create a set of the unvisited nodes called the unvisited set consisting of all the nodes except the initial node.
[3]For the current node, consider all of its unvisited neighbors and calculate their tentative distances.
[4]When we are done considering all of the neighbors of the current node, mark the current node as visited and remove it from the unvisited set. A visited node will never be checked again.
[5]If the destination node has been marked visited (when planning a route between two specific nodes) or if the smallest tentative
Saket Kr. Pathak Page 97
Data Structure in C (Lab. Programs)
distance among the nodes in the unvisited set is infinity (when planning a complete traversal), then stop. The algorithm has finished.
[6]Select the unvisited node that is marked with the smallest tentative distance, and set it as the new "current node" then go back to step 3.
Time Complexity –Time complexity of the following algorithm is O (M * log (N)),
where M is number of edges and N is number of vertices.