Embed presentation
Downloaded 14 times


































![Data Structures & Algorithms26ExampleResultLet LA be a Linear Array (unordered) with N elements and K is a positive integer suchthat K<=N. Following is the algorithm where ITEM is inserted into the Kthposition of LA −1. Start2. Set J=N3. Set N = N+14. Repeat steps 5 and 6 while J >= K5. Set LA[J+1] = LA[J]6. Set J = J-17. Set LA[K] = ITEM8. StopExampleFollowing is the implementation of the above algorithm −#include <stdio.h>main() {int LA[] = {1,3,5,7,8};int item = 10, k = 3, n = 5;int i = 0, j = n;printf("The original array elements are :n");for(i = 0; i<n; i++) {printf("LA[%d] = %d n", i, LA[i]);}n = n + 1;while( j >= k){LA[j+1] = LA[j];j = j - 1;}](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-35-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms27LA[k] = item;printf("The array elements after insertion :n");for(i = 0; i<n; i++) {printf("LA[%d] = %d n", i, LA[i]);}}When we compile and execute the above program, it produces the following result −The original array elements are :LA[0]=1LA[1]=3LA[2]=5LA[3]=7LA[4]=8The array elements after insertion :LA[0]=1LA[1]=3LA[2]=5LA[3]=10LA[4]=7LA[5]=8For other variations of array insertion operation click hereArrayInsertionsIn the previous section, we have learnt how the insertion operation works. It is not alwaysnecessary that an element is inserted at the end of an array. Following can be a situationwith array insertion − Insertion at the beginning of an array Insertion at the given index of an array Insertion after the given index of an array Insertion before the given index of an array](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-36-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms28InsertionattheBeginningofanArrayWhen the insertion happens at the beginning, it causes all the existing data items to shiftone step downward. Here, we design and implement an algorithm to insert an element atthe beginning of an array.AlgorithmWe assume A is an array with N elements. The maximum numbers of elements it canstore is defined by MAX. We shall first check if an array has any empty space to store anyelement and then we proceed with the insertion process.beginIF N = MAX, returnELSEN = N + 1For All Elements in AMove to next adjacent locationA[FIRST] = New_ElementendImplementation in C#include <stdio.h>#define MAX 5void main() {int array[MAX] = {2, 3, 4, 5};int N = 4; // number of elements in arrayint i = 0; // loop variableint value = 1; // new data element to be stored in array// print array before insertionprintf("Printing array before insertion −n");](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-37-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms29for(i = 0; i < N; i++) {printf("array[%d] = %d n", i, array[i]);}// now shift rest of the elements downwardsfor(i = N; i >= 0; i--) {array[i+1] = array[i];}// add new element at first positionarray[0] = value;// increase N to reflect number of elementsN++;// print to confirmprintf("Printing array after insertion −n");for(i = 0; i < N; i++) {printf("array[%d] = %dn", i, array[i]);}}This program should yield the following output −Printing array before insertion −array[0] = 2array[1] = 3array[2] = 4array[3] = 5Printing array after insertion −array[0] = 0array[1] = 2array[2] = 3array[3] = 4array[4] = 5](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-38-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms30InsertionattheGivenIndexofanArrayIn this scenario, we are given the exact location (index) of an array where a new dataelement (value) needs to be inserted. First we shall check if the array is full, if it is not,then we shall move all data elements from that location one step downward. This will makeroom for a new data element.AlgorithmWe assume A is an array with N elements. The maximum numbers of elements it canstore is defined by MAX.beginIF N = MAX, returnELSEN = N + 1SEEK Location indexFor All Elements from A[index] to A[N]Move to next adjacent locationA[index] = New_ElementendImplementation in C#include <stdio.h>#define MAX 5void main() {int array[MAX] = {1, 2, 4, 5};int N = 4; // number of elements in arrayint i = 0; // loop variableint index = 2; // index location to insert new valueint value = 3; // new data element to be inserted// print array before insertionprintf("Printing array before insertion −n");](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-39-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms31for(i = 0; i < N; i++) {printf("array[%d] = %d n", i, array[i]);}// now shift rest of the elements downwardsfor(i = N; i >= index; i--) {array[i+1] = array[i];}// add new element at first positionarray[index] = value;// increase N to reflect number of elementsN++;// print to confirmprintf("Printing array after insertion −n");for(i = 0; i < N; i++) {printf("array[%d] = %dn", i, array[i]);}}If we compile and run the above program, it will produce the following result −Printing array before insertion −array[0] = 1array[1] = 2array[2] = 4array[3] = 5Printing array after insertion −array[0] = 1array[1] = 2array[2] = 3array[3] = 4array[4] = 5](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-40-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms32InsertionAftertheGivenIndexofanArrayIn this scenario we are given a location (index) of an array after which a new data element(value) has to be inserted. Only the seek process varies, the rest of the activities are thesame as in the previous example.AlgorithmWe assume A is an array with N elements. The maximum numbers of elements it canstore is defined by MAX.beginIF N = MAX, returnELSEN = N + 1SEEK Location indexFor All Elements from A[index + 1] to A[N]Move to next adjacent locationA[index + 1] = New_ElementendImplementation in C#include <stdio.h>#define MAX 5void main() {int array[MAX] = {1, 2, 4, 5};int N = 4; // number of elements in arrayint i = 0; // loop variableint index = 1; // index location after which value will be insertedint value = 3; // new data element to be inserted// print array before insertionprintf("Printing array before insertion −n");](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-41-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms33for(i = 0; i < N; i++) {printf("array[%d] = %d n", i, array[i]);}// now shift rest of the elements downwardsfor(i = N; i >= index + 1; i--) {array[i + 1] = array[i];}// add new element at first positionarray[index + 1] = value;// increase N to reflect number of elementsN++;// print to confirmprintf("Printing array after insertion −n");for(i = 0; i < N; i++) {printf("array[%d] = %dn", i, array[i]);}}If we compile and run the above program, it will produce the following result −Printing array before insertion −array[0] = 1array[1] = 2array[2] = 4array[3] = 5Printing array after insertion −array[0] = 1array[1] = 2array[2] = 3array[3] = 4](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-42-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms34array[4] = 5InsertionBeforetheGivenIndexofanArrayIn this scenario we are given a location (index) of an array before which a new dataelement (value) has to be inserted. This time we seek till index-1, i.e., one locationahead of the given index. Rest of the activities are the same as in the previous example.AlgorithmWe assume A is an array with N elements. The maximum numbers of elements it canstore is defined by MAX.beginIF N = MAX, returnELSEN = N + 1SEEK Location indexFor All Elements from A[index - 1] to A[N]Move to next adjacent locationA[index - 1] = New_ElementendImplementation in C#include <stdio.h>#define MAX 5](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-43-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms35void main() {int array[MAX] = {1, 2, 4, 5};int N = 4; // number of elements in arrayint i = 0; // loop variableint index = 3; // index location before which value will be insertedint value = 3; // new data element to be inserted// print array before insertionprintf("Printing array before insertion −n");for(i = 0; i < N; i++) {printf("array[%d] = %d n", i, array[i]);}// now shift rest of the elements downwardsfor(i = N; i >= index + 1; i--) {array[i + 1] = array[i];}// add new element at first positionarray[index + 1] = value;// increase N to reflect number of elementsN++;// print to confirmprintf("Printing array after insertion −n");for(i = 0; i < N; i++) {printf("array[%d] = %dn", i, array[i]);}}If we compile and run the above program, it will produce the following result −Printing array before insertion −array[0] = 1array[1] = 2](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-44-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms36array[2] = 4array[3] = 5Printing array after insertion −array[0] = 1array[1] = 2array[2] = 4array[3] = 5array[4] = 3DeletionOperationDeletion refers to removing an existing element from the array and re-organizing allelements of an array.AlgorithmConsider LA is a linear array with N elements and K is a positive integer such that K<=N.Following is the algorithm to delete an element available at the Kthposition of LA.1. Start2. Set J=K3. Repeat steps 4 and 5 while J < N4. Set LA[J-1] = LA[J]5. Set J = J+16. Set N = N-17. StopExampleFollowing is the implementation of the above algorithm −#include <stdio.h>main() {int LA[] = {1,3,5,7,8};int k = 3, n = 5;int i, j;printf("The original array elements are :n");](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-45-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms37for(i = 0; i<n; i++) {printf("LA[%d] = %d n", i, LA[i]);}j = k;while( j < n){LA[j-1] = LA[j];j = j + 1;}n = n -1;printf("The array elements after deletion :n");for(i = 0; i<n; i++) {printf("LA[%d] = %d n", i, LA[i]);}}When we compile and execute the above program, it produces the following result −The original array elements are :LA[0]=1LA[1]=3LA[2]=5LA[3]=7LA[4]=8The array elements after deletion :LA[0]=1LA[1]=3LA[2]=7LA[3]=8SearchOperationYou can perform a search for an array element based on its value or its index.Algorithm](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-46-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms38Consider LA is a linear array with N elements and K is a positive integer such that K<=N.Following is the algorithm to find an element with a value of ITEM using sequential search.1. Start2. Set J=03. Repeat steps 4 and 5 while J < N4. IF LA[J] is equal ITEM THEN GOTO STEP 65. Set J = J +16. PRINT J, ITEM7. StopExampleFollowing is the implementation of the above algorithm −#include <stdio.h>main() {int LA[] = {1,3,5,7,8};int item = 5, n = 5;int i = 0, j = 0;printf("The original array elements are :n");for(i = 0; i<n; i++) {printf("LA[%d] = %d n", i, LA[i]);}while( j < n){if( LA[j] == item ){break;}j = j + 1;}printf("Found element %d at position %dn", item, j+1);}When we compile and execute the above program, it produces the following result −](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-47-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms39The original array elements are :LA[0]=1LA[1]=3LA[2]=5LA[3]=7LA[4]=8Found element 5 at position 3UpdateOperationUpdate operation refers to updating an existing element from the array at a given index.AlgorithmConsider LA is a linear array with N elements and K is a positive integer such that K<=N.Following is the algorithm to update an element available at the Kthposition of LA.1. Start2. Set LA[K-1] = ITEM3. StopExampleFollowing is the implementation of the above algorithm −#include <stdio.h>main() {int LA[] = {1,3,5,7,8};int k = 3, n = 5, item = 10;int i, j;printf("The original array elements are :n");for(i = 0; i<n; i++) {printf("LA[%d] = %d n", i, LA[i]);}LA[k-1] = item;printf("The array elements after updation :n");](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-48-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms40for(i = 0; i<n; i++) {printf("LA[%d] = %d n", i, LA[i]);}}When we compile and execute the above program, it produces the following result −The original array elements are :LA[0]=1LA[1]=3LA[2]=5LA[3]=7LA[4]=8The array elements after updation :LA[0]=1LA[1]=3LA[2]=10LA[3]=7LA[4]=8](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-49-2048.jpg&f=jpg&w=240)






![Data Structures & Algorithms47Implementation in C#include <stdio.h>#include <string.h>#include <stdlib.h>#include <stdbool.h>struct node{int data;int key;struct node *next;};struct node *head = NULL;struct node *current = NULL;//display the listvoid printList(){struct node *ptr = head;printf("n[ ");//start from the beginningwhile(ptr != NULL){printf("(%d,%d) ",ptr->key,ptr->data);ptr = ptr->next;}printf(" ]");}//insert link at the first locationvoid insertFirst(int key, int data){//create a link](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-56-2048.jpg&f=jpg&w=240)






![Data Structures & Algorithms54printf("nList after reversing the data: ");printList();}If we compile and run the above program, it will produce the following result −Original List:[ (6,56) (5,40) (4,1) (3,30) (2,20) (1,10) ]Deleted value:(6,56)Deleted value:(5,40)Deleted value:(4,1)Deleted value:(3,30)Deleted value:(2,20)Deleted value:(1,10)List after deleting all items:[ ]Restored List:[ (6,56) (5,40) (4,1) (3,30) (2,20) (1,10) ]Element found: (4,1)List after deleting an item:[ (6,56) (5,40) (3,30) (2,20) (1,10) ]Element not found.List after sorting the data:[ (1,10) (2,20) (3,30) (5,40) (6,56) ]List after reversing the data:[ (6,56) (5,40) (3,30) (2,20) (1,10) ]](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-63-2048.jpg&f=jpg&w=240)





![Data Structures & Algorithms60printf(" ]");}//display the list from last to firstvoid displayBackward(){//start from the laststruct node *ptr = last;//navigate till the start of the listprintf("n[ ");while(ptr != NULL){//print dataprintf("(%d,%d) ",ptr->key,ptr->data);//move to next itemptr = ptr ->prev;printf(" ");}printf(" ]");}//insert link at the first locationvoid insertFirst(int key, int data){//create a linkstruct node *link = (struct node*) malloc(sizeof(struct node));link->key = key;link->data = data;if(isEmpty()){//make it the last linklast = link;](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-69-2048.jpg&f=jpg&w=240)





![Data Structures & Algorithms66deleteLast();displayForward();printf("nList , insert after key(4) : ");insertAfter(4,7, 13);displayForward();printf("nList , after delete key(4) : ");delete(4);displayForward();}If we compile and run the above program, it will produce the following result −List (First to Last):[ (6,56) (5,40) (4,1) (3,30) (2,20) (1,10) ]List (Last to first):[ (1,10) (2,20) (3,30) (4,1) (5,40) (6,56) ]List , after deleting first record:[ (5,40) (4,1) (3,30) (2,20) (1,10) ]List , after deleting last record:[ (5,40) (4,1) (3,30) (2,20) ]List , insert after key(4) :[ (5,40) (4,1) (4,13) (3,30) (2,20) ]List , after delete key(4) :[ (5,40) (4,13) (3,30) (2,20) ]](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-75-2048.jpg&f=jpg&w=240)


![Data Structures & Algorithms69//mark next to first link as firsthead = head->next;//return the deleted linkreturn tempLink;}DisplayListOperationFollowing code demonstrates the display list operation in a circular linked list.//display the listvoid printList() {struct node *ptr = head;printf("n[ ");//start from the beginningif(head != NULL) {while(ptr->next != ptr) {printf("(%d,%d) ",ptr->key,ptr->data);ptr = ptr->next;}}printf(" ]");}To know about its implementation in C programming language, please click here.CircularLinkedListPrograminCCircular Linked List is a variation of Linked list in which the first element points to the lastelement and the last element points to the first element. Both Singly Linked List andDoubly Linked List can be made into a circular linked list.](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-78-2048.jpg&f=jpg&w=240)


![Data Structures & Algorithms72//mark next to first link as firsthead = head->next;//return the deleted linkreturn tempLink;}//display the listvoid printList(){struct node *ptr = head;printf("n[ ");//start from the beginningif(head != NULL){while(ptr->next != ptr){printf("(%d,%d) ",ptr->key,ptr->data);ptr = ptr->next;}}printf(" ]");}main() {insertFirst(1,10);insertFirst(2,20);insertFirst(3,30);insertFirst(4,1);insertFirst(5,40);insertFirst(6,56);](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-81-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms73printf("Original List: ");//print listprintList();while(!isEmpty()){struct node *temp = deleteFirst();printf("nDeleted value:");printf("(%d,%d) ",temp->key,temp->data);}printf("nList after deleting all items: ");printList();}If we compile and run the above program, it will produce the following result −Original List:[ (6,56) (5,40) (4,1) (3,30) (2,20) ]Deleted value:(6,56)Deleted value:(5,40)Deleted value:(4,1)Deleted value:(3,30)Deleted value:(2,20)Deleted value:(1,10)List after deleting all items:[ ]](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-82-2048.jpg&f=jpg&w=240)


![Data Structures & Algorithms76BasicOperationsStack operations may involve initializing the stack, using it and then de-initializing it. Apartfrom these basic stuffs, a stack is used for the following two primary operations − push() − Pushing (storing) an element on the stack. pop() − Removing (accessing) an element from the stack.When data is PUSHed onto stack.To use a stack efficiently, we need to check the status of stack as well. For the samepurpose, the following functionality is added to stacks − peek() − get the top data element of the stack, without removing it. isFull() − check if stack is full. isEmpty() − check if stack is empty.At all times, we maintain a pointer to the last PUSHed data on the stack. As this pointeralways represents the top of the stack, hence named top. The top pointer provides topvalue of the stack without actually removing it.First we should learn about procedures to support stack functions −peek()Algorithm of peek() function −begin procedure peekreturn stack[top]end procedureImplementation of peek() function in C programming language −int peek() {return stack[top];}](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-85-2048.jpg&f=jpg&w=240)


![Data Structures & Algorithms79If the linked list is used to implement the stack, then in step 3, we need to allocate spacedynamically.Algorithm for PUSH OperationA simple algorithm for Push operation can be derived as follows −begin procedure push: stack, dataif stack is fullreturn nullendiftop ← top + 1stack[top] ← dataend procedureImplementation of this algorithm in C, is very easy. See the following code −void push(int data) {if(!isFull()) {top = top + 1;stack[top] = data;}else {printf("Could not insert data, Stack is full.n");}}PopOperationAccessing the content while removing it from the stack, is known as a Pop Operation. Inan array implementation of pop() operation, the data element is not actually removed,instead top is decremented to a lower position in the stack to point to the next value. Butin linked-list implementation, pop() actually removes data element and deallocatesmemory space.A Pop operation may involve the following steps − Step 1 − Checks if the stack is empty. Step 2 − If the stack is empty, produces an error and exit.](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-88-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms80 Step 3 − If the stack is not empty, accesses the data element at which top ispointing. Step 4 − Decreases the value of top by 1. Step 5 − Returns success.Algorithm for Pop OperationA simple algorithm for Pop operation can be derived as follows −begin procedure pop: stackif stack is emptyreturn nullendifdata ← stack[top]top ← top - 1return dataend procedure](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-89-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms81Implementation of this algorithm in C, is as follows −int pop(int data) {if(!isempty()) {data = stack[top];top = top - 1;return data;}else {printf("Could not retrieve data, Stack is empty.n");}}For a complete stack program in C programming language, please click here.StackPrograminCWe shall see the stack implementation in C programming language here. You can try theprogram by clicking on the Try-it button. To learn the theory aspect of stacks, click on visitprevious page.Implementation in C#include <stdio.h>int MAXSIZE = 8;int stack[8];int top = -1;int isempty() {if(top == -1)return 1;elsereturn 0;}](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-90-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms82int isfull() {if(top == MAXSIZE)return 1;elsereturn 0;}int peek() {return stack[top];}int pop() {int data;if(!isempty()) {data = stack[top];top = top - 1;return data;}else {printf("Could not retrieve data, Stack is empty.n");}}int push(int data) {if(!isfull()) {top = top + 1;stack[top] = data;}else {printf("Could not insert data, Stack is full.n");}}](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-91-2048.jpg&f=jpg&w=240)




![Data Structures & Algorithms87In a+b*c, the expression part b*c will be evaluated first, with multiplication asprecedence over addition. We here use parenthesis for a+b to be evaluated first,like (a+b)*c.PostfixEvaluationAlgorithmWe shall now look at the algorithm on how to evaluate postfix notation −Step 1 − scan the expression from left to rightStep 2 − if it is an operand push it to stackStep 3 − if it is an operator pull operand from stack and perform operationStep 4 − store the output of step 3, back to stackStep 5 − scan the expression until all operands are consumedStep 6 − pop the stack and perform operationTo see the implementation in C programming language, please click hereExpressionParsingUsingStackInfix notation is easier for humans to read and understand whereas for electronic machineslike computers, postfix is the best form of expression to parse. We shall see here a programto convert and evaluate infix notation to postfix notation −#include<stdio.h>#include<string.h>//char stackchar stack[25];int top = -1;void push(char item) {stack[++top] = item;}char pop() {return stack[top--];}](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-96-2048.jpg&f=jpg&w=240)

![Data Structures & Algorithms89default:return 0;}}//converts infix expression to postfixvoid convert(char infix[],char postfix[]) {int i,symbol,j = 0;stack[++top] = '#';for(i = 0;i<strlen(infix);i++) {symbol = infix[i];if(isOperator(symbol) == 0) {postfix[j] = symbol;j++;} else {if(symbol == '(') {push(symbol);}else {if(symbol == ')') {while(stack[top] != '(') {postfix[j] = pop();j++;}pop();//pop out (.} else {if(precedence(symbol)>precedence(stack[top])) {push(symbol);}else {while(precedence(symbol)<=precedence(stack[top])) {postfix[j] = pop();j++;}](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-98-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms90push(symbol);}}}}}while(stack[top] != '#') {postfix[j] = pop();j++;}postfix[j]='0';//null terminate string.}//int stackint stack_int[25];int top_int = -1;void push_int(int item) {stack_int[++top_int] = item;}char pop_int() {return stack_int[top_int--];}//evaluates postfix expressionint evaluate(char *postfix){char ch;int i = 0,operand1,operand2;while( (ch = postfix[i++]) != '0') {if(isdigit(ch)) {](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-99-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms91push_int(ch-'0'); // Push the operand}else {//Operator,pop two operandsoperand2 = pop_int();operand1 = pop_int();switch(ch) {case '+':push_int(operand1+operand2);break;case '-':push_int(operand1-operand2);break;case '*':push_int(operand1*operand2);break;case '/':push_int(operand1/operand2);break;}}}return stack_int[top_int];}void main() {char infix[25] = "1*(2+3)",postfix[25];convert(infix,postfix);printf("Infix expression is: %sn" , infix);printf("Postfix expression is: %sn" , postfix);printf("Evaluated expression is: %dn" , evaluate(postfix));}](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-100-2048.jpg&f=jpg&w=240)


![Data Structures & Algorithms94Few more functions are required to make the above-mentioned queue operation efficient.These are − peek() − Gets the element at the front of the queue without removing it. isfull() − Checks if the queue is full. isempty() − Checks if the queue is empty.In queue, we always dequeue (or access) data, pointed by front pointer and whileenqueing (or storing) data in the queue we take help of rear pointer.Let's first learn about supportive functions of a queue −peek()This function helps to see the data at the front of the queue. The algorithm of peek()function is as follows −begin procedure peekreturn queue[front]end procedureImplementation of peek() function in C programming language −int peek() {return queue[front];}isfull()As we are using single dimension array to implement queue, we just check for the rearpointer to reach at MAXSIZE to determine that the queue is full. In case we maintain thequeue in a circular linked-list, the algorithm will differ. Algorithm of isfull() function −begin procedure isfullif rear equals to MAXSIZEreturn trueelse](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-103-2048.jpg&f=jpg&w=240)


![Data Structures & Algorithms97Algorithm for enqueue Operationprocedure enqueue(data)if queue is fullreturn overflowendifrear ← rear + 1queue[rear] ← datareturn trueend procedureImplementation of enqueue() in C programming language −int enqueue(int data)if(isfull())return 0;rear = rear + 1;queue[rear] = data;return 1;end procedureDequeueOperationAccessing data from the queue is a process of two tasks − access the data where front ispointing and remove the data after access. The following steps are taken toperform dequeue operation − Step 1 − Check if the queue is empty. Step 2 − If the queue is empty, produce underflow error and exit. Step 3 − If the queue is not empty, access the data where front is pointing. Step 4 − Increment front pointer to point to the next available data element. Step 5 − Return success.](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-106-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms98Algorithm for dequeue Operationprocedure dequeueif queue is emptyreturn underflowend ifdata = queue[front]front ← front + 1return trueend procedureImplementation of dequeue() in C programming language −int dequeue() {if(isempty())return 0;int data = queue[front];front = front + 1;return data;}For a complete Queue program in C programming language, please click here.](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-107-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms99QueuePrograminCWe shall see the stack implementation in C programming language here. You can try theprogram by clicking on the Try-it button. To learn the theory aspect of stacks, click on visitprevious page.Implementation in C#include <stdio.h>#include <string.h>#include <stdlib.h>#include <stdbool.h>#define MAX 6int intArray[MAX];int front = 0;int rear = -1;int itemCount = 0;int peek(){return intArray[front];}bool isEmpty(){return itemCount == 0;}bool isFull(){return itemCount == MAX;}int size(){return itemCount;}void insert(int data){if(!isFull()){](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-108-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms100if(rear == MAX-1){rear = -1;}intArray[++rear] = data;itemCount++;}}int removeData(){int data = intArray[front++];if(front == MAX){front = 0;}itemCount--;return data;}int main() {/* insert 5 items */insert(3);insert(5);insert(9);insert(1);insert(12);// front : 0// rear : 4// ------------------// index : 0 1 2 3 4// ------------------// queue : 3 5 9 1 12insert(15);// front : 0// rear : 5](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-109-2048.jpg&f=jpg&w=240)



![Data Structures & Algorithms104Linear search is a very simple search algorithm. In this type of search, a sequential searchis made over all items one by one. Every item is checked and if a match is found then thatparticular item is returned, otherwise the search continues till the end of the datacollection.AlgorithmLinear Search ( Array A, Value x)Step 1: Set i to 1Step 2: if i > n then go to step 7Step 3: if A[i] = x then go to step 6Step 4: Set i to i + 1Step 5: Go to Step 2Step 6: Print Element x Found at index i and go to step 8Step 7: Print element not foundStep 8: ExitPseudocodeprocedure linear_search (list, value)for each item in the listif match item == valuereturn the item's location16. Linear Search](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-113-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms105end ifend forend procedureTo know about linear search implementation in C programming language, please click-here.LinearSearchPrograminCHere we present the implementation of linear search in C programming language. Theoutput of the program is given after the code.Linear Search Program#include <stdio.h>#define MAX 20// array of items on which linear search will be conducted.int intArray[MAX] = {1,2,3,4,6,7,9,11,12,14,15,16,17,19,33,34,43,45,55,66};void printline(int count){int i;for(i = 0;i <count-1;i++){printf("=");}printf("=n");}// this method makes a linear search.int find(int data){int comparisons = 0;int index = -1;int i;](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-114-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms106// navigate through all itemsfor(i = 0;i<MAX;i++){// count the comparisons madecomparisons++;// if data found, break the loopif(data == intArray[i]){index = i;break;}}printf("Total comparisons made: %d", comparisons);return index;}void display(){int i;printf("[");// navigate through all itemsfor(i = 0;i<MAX;i++){printf("%d ",intArray[i]);}printf("]n");}main(){printf("Input Array: ");display();printline(50);](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-115-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms107//find location of 1int location = find(55);// if element was foundif(location != -1)printf("nElement found at location: %d" ,(location+1));elseprintf("Element not found.");}If we compile and run the above program, it will produce the following result −Input Array: [1 2 3 4 6 7 9 11 12 14 15 16 17 19 33 34 43 45 55 66 ]==================================================Total comparisons made: 19Element found at location: 19](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-116-2048.jpg&f=jpg&w=240)


![Data Structures & Algorithms110PseudocodeThe pseudocode of binary search algorithms should look like this −Procedure binary_searchA ← sorted arrayn ← size of arrayx ← value ot be searchedSet lowerBound = 1Set upperBound = nwhile x not foundif upperBound < lowerBoundEXIT: x does not exists.set midPoint = lowerBound + ( upperBound - lowerBound ) / 2if A[midPoint] < xset lowerBound = midPoint + 1if A[midPoint] > xset upperBound = midPoint - 1if A[midPoint] = xEXIT: x found at location midPointend whileend procedureTo know about binary search implementation using array in C programming language,please click here.](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-119-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms111BinarySearchPrograminCBinary search is a fast search algorithm with run-time complexity of Ο(log n). This searchalgorithm works on the principle of divide and conquer. For this algorithm to work properly,the data collection should be in a sorted form.Implementation in C#include <stdio.h>#define MAX 20// array of items on which linear search will be conducted.int intArray[MAX] = {1,2,3,4,6,7,9,11,12,14,15,16,17,19,33,34,43,45,55,66};void printline(int count){int i;for(i = 0;i <count-1;i++){printf("=");}printf("=n");}int find(int data){int lowerBound = 0;int upperBound = MAX -1;int midPoint = -1;int comparisons = 0;int index = -1;while(lowerBound <= upperBound){printf("Comparison %dn" , (comparisons +1) ) ;printf("lowerBound : %d, intArray[%d] = %dn",lowerBound,lowerBound,intArray[lowerBound]);printf("upperBound : %d, intArray[%d] = %dn",upperBound,upperBound,intArray[upperBound]);](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-120-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms112comparisons++;// compute the mid point// midPoint = (lowerBound + upperBound) / 2;midPoint = lowerBound + (upperBound - lowerBound) / 2;// data foundif(intArray[midPoint] == data){index = midPoint;break;}else {// if data is largerif(intArray[midPoint] < data){// data is in upper halflowerBound = midPoint + 1;}// data is smallerelse{// data is in lower halfupperBound = midPoint -1;}}}printf("Total comparisons made: %d" , comparisons);return index;}void display(){int i;printf("[");// navigate through all itemsfor(i = 0;i<MAX;i++){printf("%d ",intArray[i]);}](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-121-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms113printf("]n");}main(){printf("Input Array: ");display();printline(50);//find location of 1int location = find(55);// if element was foundif(location != -1)printf("nElement found at location: %d" ,(location+1));elseprintf("nElement not found.");}If we compile and run the above program, it will produce the following result −Input Array: [1 2 3 4 6 7 9 11 12 14 15 16 17 19 33 34 43 45 55 66 ]==================================================Comparison 1lowerBound : 0, intArray[0] = 1upperBound : 19, intArray[19] = 66Comparison 2lowerBound : 10, intArray[10] = 15upperBound : 19, intArray[19] = 66Comparison 3lowerBound : 15, intArray[15] = 34upperBound : 19, intArray[19] = 66Comparison 4lowerBound : 18, intArray[18] = 55upperBound : 19, intArray[19] = 66Total comparisons made: 4Element found at location: 19](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-122-2048.jpg&f=jpg&w=240)


![Data Structures & Algorithms116PositionProbinginInterpolationSearchInterpolation search finds a particular item by computing the probe position. Initially, theprobe position is the position of the middle most item of the collection.If a match occurs, then the index of the item is returned. To split the list into two parts,we use the following method −mid = Lo + ((Hi - Lo) / (A[Hi] - A[Lo])) * (X - A[Lo])where −A = listLo = Lowest index of the listHi = Highest index of the listA[n] = Value stored at index n in the listIf the middle item is greater than the item, then the probe position is again calculated inthe sub-array to the right of the middle item. Otherwise, the item is searched in the sub-array to the left of the middle item. This process continues on the sub-array as well untilthe size of subarray reduces to zero.Runtime complexity of interpolation search algorithm is Ο(log (log n)) as comparedto Ο(log n) of BST in favorable situations.AlgorithmAs it is an improvisation of the existing BST algorithm, we are mentioning the steps tosearch the 'target' data value index, using position probing −Step 1 − Start searching data from middle of the list.Step 2 − If it is a match, return the index of the item, and exit.Step 3 − If it is not a match, probe position.Step 4 − Divide the list using probing formula and find the new middle.Step 5 − If data is greater than middle, search in higher sub-list.Step 6 − If data is smaller than middle, search in lower sub-list.Step 7 − Repeat until match.](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-125-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms117PseudocodeA → Array listN → Size of AX → Target ValueProcedure Interpolation_Search()Set Lo → 0Set Mid → -1Set Hi → N-1While X does not matchif Lo equals to Hi OR A[Lo] equals to A[Hi]EXIT: Failure, Target not foundend ifSet Mid = Lo + ((Hi - Lo) / (A[Hi] - A[Lo])) * (X - A[Lo])if A[Mid] = XEXIT: Success, Target found at Midelseif A[Mid] < XSet Lo to Mid+1else if A[Mid] > XSet Hi to Mid-1end ifend ifEnd WhileEnd ProcedureTo know about the implementation of interpolation search in C programminglanguage, click here.](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-126-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms118InterpolationSearchPrograminCInterpolation search is an improved variant of binary search. This search algorithm workson the probing position of the required value. For this algorithm to work properly, the datacollection should be in sorted and equally distributed form.It's runtime complexity is log2(log2 n).Implementation in C#include<stdio.h>#define MAX 10// array of items on which linear search will be conducted.int list[MAX] = { 10, 14, 19, 26, 27, 31, 33, 35, 42, 44 };int find(int data) {int lo = 0;int hi = MAX - 1;int mid = -1;int comparisons = 1;int index = -1;while(lo <= hi) {printf("nComparison %d n" , comparisons ) ;printf("lo : %d, list[%d] = %dn", lo, lo, list[lo]);printf("hi : %d, list[%d] = %dn", hi, hi, list[hi]);comparisons++;// probe the mid pointmid = lo + (((double)(hi - lo) / (list[hi] - list[lo])) * (data - list[lo]));printf("mid = %dn",mid);// data foundif(list[mid] == data) {index = mid;break;}else {](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-127-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms119if(list[mid] < data) {// if data is larger, data is in upper halflo = mid + 1;}else {// if data is smaller, data is in lower halfhi = mid - 1;}}}printf("nTotal comparisons made: %d", --comparisons);return index;}int main() {//find location of 33int location = find(33);// if element was foundif(location != -1)printf("nElement found at location: %d" ,(location+1));elseprintf("Element not found.");return 0;}If we compile and run the above program, it will produce the following result −Comparison 1lo : 0, list[0] = 10hi : 9, list[9] = 44mid = 6Total comparisons made: 1Element found at location: 7You can change the search value and execute the program to test it.](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-128-2048.jpg&f=jpg&w=240)



![Data Structures & Algorithms123struct DataItem *search(int key){//get the hashint hashIndex = hashCode(key);//move in array until an emptywhile(hashArray[hashIndex] != NULL){if(hashArray[hashIndex]->key == key)return hashArray[hashIndex];//go to next cell++hashIndex;//wrap around the tablehashIndex %= SIZE;}return NULL;}InsertOperationWhenever an element is to be inserted, compute the hash code of the key passed andlocate the index using that hash code as an index in the array. Use linear probing forempty location, if an element is found at the computed hash code.void insert(int key,int data){struct DataItem *item = (struct DataItem*) malloc(sizeof(struct DataItem));item->data = data;item->key = key;//get the hashint hashIndex = hashCode(key);//move in array until an empty or deleted cellwhile(hashArray[hashIndex] != NULL && hashArray[hashIndex]->key != -1){//go to next cell++hashIndex;](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-132-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms124//wrap around the tablehashIndex %= SIZE;}hashArray[hashIndex] = item;}DeleteOperationWhenever an element is to be deleted, compute the hash code of the key passed andlocate the index using that hash code as an index in the array. Use linear probing to getthe element ahead if an element is not found at the computed hash code. When found,store a dummy item there to keep the performance of the hash table intact.struct DataItem* delete(struct DataItem* item){int key = item->key;//get the hashint hashIndex = hashCode(key);//move in array until an emptywhile(hashArray[hashIndex] !=NULL){if(hashArray[hashIndex]->key == key){struct DataItem* temp = hashArray[hashIndex];//assign a dummy item at deleted positionhashArray[hashIndex] = dummyItem;return temp;}//go to next cell++hashIndex;//wrap around the tablehashIndex %= SIZE;}return NULL;}](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-133-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms125To know about hash implementation in C programming language, please click here.HashTablePrograminCHash Table is a data structure which stores data in an associative manner. In hash table,the data is stored in an array format where each data value has its own unique indexvalue. Access of data becomes very fast, if we know the index of the desired data.Implementation in C#include <stdio.h>#include <string.h>#include <stdlib.h>#include <stdbool.h>#define SIZE 20struct DataItem {int data;int key;};struct DataItem* hashArray[SIZE];struct DataItem* dummyItem;struct DataItem* item;int hashCode(int key){return key % SIZE;}struct DataItem *search(int key){//get the hashint hashIndex = hashCode(key);//move in array until an emptywhile(hashArray[hashIndex] != NULL){if(hashArray[hashIndex]->key == key)return hashArray[hashIndex];](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-134-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms126//go to next cell++hashIndex;//wrap around the tablehashIndex %= SIZE;}return NULL;}void insert(int key,int data){struct DataItem *item = (struct DataItem*) malloc(sizeof(struct DataItem));item->data = data;item->key = key;//get the hashint hashIndex = hashCode(key);//move in array until an empty or deleted cellwhile(hashArray[hashIndex] != NULL && hashArray[hashIndex]->key != -1){//go to next cell++hashIndex;//wrap around the tablehashIndex %= SIZE;}hashArray[hashIndex] = item;}struct DataItem* delete(struct DataItem* item){int key = item->key;//get the hash](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-135-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms127int hashIndex = hashCode(key);//move in array until an emptywhile(hashArray[hashIndex] != NULL){if(hashArray[hashIndex]->key == key){struct DataItem* temp = hashArray[hashIndex];//assign a dummy item at deleted positionhashArray[hashIndex] = dummyItem;return temp;}//go to next cell++hashIndex;//wrap around the tablehashIndex %= SIZE;}return NULL;}void display(){int i = 0;for(i = 0; i<SIZE; i++) {if(hashArray[i] != NULL)printf(" (%d,%d)",hashArray[i]->key,hashArray[i]->data);elseprintf(" ~~ ");}printf("n");}](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-136-2048.jpg&f=jpg&w=240)









![Data Structures & Algorithms137AlgorithmWe assume list is an array of n elements. We further assume that swap function swapsthe values of the given array elements.begin BubbleSort(list)for all elements of listif list[i] > list[i+1]swap(list[i], list[i+1])end ifend forreturn listend BubbleSortPseudocodeWe observe in algorithm that Bubble Sort compares each pair of array element unless thewhole array is completely sorted in an ascending order. This may cause a few complexityissues like what if the array needs no more swapping as all the elements are alreadyascending.To ease-out the issue, we use one flag variable swapped which will help us see if anyswap has happened or not. If no swap has occurred, i.e. the array requires no moreprocessing to be sorted, it will come out of the loop.Pseudocode of BubbleSort algorithm can be written as follows −procedure bubbleSort( list : array of items )loop = list.count;for i = 0 to loop-1 do:swapped = falsefor j = 0 to loop-1 do:/* compare the adjacent elements */if list[j] > list[j+1] then/* swap them */swap( list[j], list[j+1] )](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-146-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms138swapped = trueend ifend for/*if no number was swapped that meansarray is sorted now, break the loop.*/if(not swapped) thenbreakend ifend forend procedure return listImplementationOne more issue we did not address in our original algorithm and its improvisedpseudocode, is that, after every iteration the highest values settles down at the end of thearray. Hence, the next iteration need not include already sorted elements. For thispurpose, in our implementation, we restrict the inner loop to avoid already sorted values.To know about bubble sort implementation in C programming language, please click here.BubbleSortPrograminCWe shall see the implementation of bubble sort in C programming language here.Implementation in C#include <stdio.h>#include <stdbool.h>#define MAX 10int list[MAX] = {1,8,4,6,0,3,5,2,7,9};void display(){int i;printf("[");](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-147-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms139// navigate through all itemsfor(i = 0; i < MAX; i++){printf("%d ",list[i]);}printf("]n");}void bubbleSort() {int temp;int i,j;bool swapped = false;// loop through all numbersfor(i = 0; i < MAX-1; i++) {swapped = false;// loop through numbers falling aheadfor(j = 0; j < MAX-1-i; j++) {printf(" Items compared: [ %d, %d ] ", list[j],list[j+1]);// check if next number is lesser than current no// swap the numbers.// (Bubble up the highest number)if(list[j] > list[j+1]) {temp = list[j];list[j] = list[j+1];list[j+1] = temp;swapped = true;printf(" => swapped [%d, %d]n",list[j],list[j+1]);}else {printf(" => not swappedn");}](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-148-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms140}// if no number was swapped that means// array is sorted now, break the loop.if(!swapped) {break;}printf("Iteration %d#: ",(i+1));display();}}main(){printf("Input Array: ");display();printf("n");bubbleSort();printf("nOutput Array: ");display();}If we compile and run the above program, it will produce the following result −Input Array: [1 8 4 6 0 3 5 2 7 9 ]Items compared: [ 1, 8 ] => not swappedItems compared: [ 8, 4 ] => swapped [4, 8]Items compared: [ 8, 6 ] => swapped [6, 8]Items compared: [ 8, 0 ] => swapped [0, 8]Items compared: [ 8, 3 ] => swapped [3, 8]Items compared: [ 8, 5 ] => swapped [5, 8]Items compared: [ 8, 2 ] => swapped [2, 8]Items compared: [ 8, 7 ] => swapped [7, 8]Items compared: [ 8, 9 ] => not swapped](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-149-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms141Iteration 1#: [1 4 6 0 3 5 2 7 8 9 ]Items compared: [ 1, 4 ] => not swappedItems compared: [ 4, 6 ] => not swappedItems compared: [ 6, 0 ] => swapped [0, 6]Items compared: [ 6, 3 ] => swapped [3, 6]Items compared: [ 6, 5 ] => swapped [5, 6]Items compared: [ 6, 2 ] => swapped [2, 6]Items compared: [ 6, 7 ] => not swappedItems compared: [ 7, 8 ] => not swappedIteration 2#: [1 4 0 3 5 2 6 7 8 9 ]Items compared: [ 1, 4 ] => not swappedItems compared: [ 4, 0 ] => swapped [0, 4]Items compared: [ 4, 3 ] => swapped [3, 4]Items compared: [ 4, 5 ] => not swappedItems compared: [ 5, 2 ] => swapped [2, 5]Items compared: [ 5, 6 ] => not swappedItems compared: [ 6, 7 ] => not swappedIteration 3#: [1 0 3 4 2 5 6 7 8 9 ]Items compared: [ 1, 0 ] => swapped [0, 1]Items compared: [ 1, 3 ] => not swappedItems compared: [ 3, 4 ] => not swappedItems compared: [ 4, 2 ] => swapped [2, 4]Items compared: [ 4, 5 ] => not swappedItems compared: [ 5, 6 ] => not swappedIteration 4#: [0 1 3 2 4 5 6 7 8 9 ]Items compared: [ 0, 1 ] => not swappedItems compared: [ 1, 3 ] => not swappedItems compared: [ 3, 2 ] => swapped [2, 3]Items compared: [ 3, 4 ] => not swappedItems compared: [ 4, 5 ] => not swappedIteration 5#: [0 1 2 3 4 5 6 7 8 9 ]Items compared: [ 0, 1 ] => not swappedItems compared: [ 1, 2 ] => not swappedItems compared: [ 2, 3 ] => not swappedItems compared: [ 3, 4 ] => not swappedOutput Array: [0 1 2 3 4 5 6 7 8 9 ]](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-150-2048.jpg&f=jpg&w=240)


![Data Structures & Algorithms144We swap them again. By the end of third iteration, we have a sorted sub-list of 4 items.This process goes on until all the unsorted values are covered in a sorted sub-list. Now weshall see some programming aspects of insertion sort.AlgorithmNow we have a bigger picture of how this sorting technique works, so we can derive simplesteps by which we can achieve insertion sort.Step 1 − If it is the first element, it is already sorted. return 1;Step 2 − Pick next elementStep 3 − Compare with all elements in the sorted sub-listStep 4 − Shift all the elements in the sorted sub-list that is greater than thevalue to be sortedStep 5 − Insert the valueStep 6 − Repeat until list is sortedPseudocodeprocedure insertionSort( A : array of items )int holePositionint valueToInsertfor i = 1 to length(A) inclusive do:/* select value to be inserted */valueToInsert = A[i]holePosition = i](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-153-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms145/*locate hole position for the element to be inserted */while holePosition > 0 and A[holePosition-1] > valueToInsert do:A[holePosition] = A[holePosition-1]holePosition = holePosition -1end while/* insert the number at hole position */A[holePosition] = valueToInsertend forend procedureTo know about insertion sort implementation in C programming language, please clickhere.InsertionSortPrograminCThis is an in-place comparison-based sorting algorithm. Here, a sub-list is maintainedwhich is always sorted. For example, the lower part of an array is maintained to be sorted.An element which is to be 'insert'ed in this sorted sub-list, has to find its appropriate placeand then it is to be inserted there. Hence the name insertion sort.Implementation in C#include <stdio.h>#include <stdbool.h>#define MAX 7int intArray[MAX] = {4,6,3,2,1,9,7};void printline(int count){int i;for(i = 0;i <count-1;i++){printf("=");}](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-154-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms146printf("=n");}void display(){int i;printf("[");// navigate through all itemsfor(i = 0;i<MAX;i++){printf("%d ",intArray[i]);}printf("]n");}void insertionSort(){int valueToInsert;int holePosition;int i;// loop through all numbersfor(i = 1; i < MAX; i++){// select a value to be inserted.valueToInsert = intArray[i];// select the hole position where number is to be insertedholePosition = i;// check if previous no. is larger than value to be insertedwhile (holePosition > 0 && intArray[holePosition-1] > valueToInsert){intArray[holePosition] = intArray[holePosition-1];holePosition--;printf(" item moved : %dn" , intArray[holePosition]);}](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-155-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms147if(holePosition != i){printf(" item inserted : %d, at position : %dn" ,valueToInsert,holePosition);// insert the number at hole positionintArray[holePosition] = valueToInsert;}printf("Iteration %d#:",i);display();}}main(){printf("Input Array: ");display();printline(50);insertionSort();printf("Output Array: ");display();printline(50);}If we compile and run the above program, it will produce the following result −Input Array: [4 6 3 2 1 9 7 ]==================================================Iteration 1#:[4 6 3 2 1 9 7 ]item moved : 6item moved : 4item inserted : 3, at position : 0Iteration 2#:[3 4 6 2 1 9 7 ]item moved : 6item moved : 4item moved : 3item inserted : 2, at position : 0Iteration 3#:[2 3 4 6 1 9 7 ]item moved : 6](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-156-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms148item moved : 4item moved : 3item moved : 2item inserted : 1, at position : 0Iteration 4#:[1 2 3 4 6 9 7 ]Iteration 5#:[1 2 3 4 6 9 7 ]item moved : 9item inserted : 7, at position : 5Iteration 6#:[1 2 3 4 6 7 9 ]Output Array: [1 2 3 4 6 7 9 ]==================================================](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-157-2048.jpg&f=jpg&w=240)


![Data Structures & Algorithms151Now, let us learn some programming aspects of selection sort.AlgorithmStep 1 − Set MIN to location 0Step 2 − Search the minimum element in the listStep 3 − Swap with value at location MINStep 4 − Increment MIN to point to next elementStep 5 − Repeat until list is sortedPseudocodeprocedure selection sortlist : array of itemsn : size of listfor i = 1 to n - 1/* set current element as minimum*/min = i/* check the element to be minimum */for j = i+1 to nif list[j] < list[min] thenmin = j;end ifend for/* swap the minimum element with the current element*/if indexMin != i thenswap list[min] and list[i]end ifend forend procedureTo know about selection sort implementation in C programming language, please clickhere.](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-160-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms152SelectionSortPrograminCSelection sort is a simple sorting algorithm. This sorting algorithm is an in-placecomparison-based algorithm in which the list is divided into two parts, the sorted part atthe left end and the unsorted part at the right end. Initially, the sorted part is empty andthe unsorted part is the entire list.Implementation in C#include <stdio.h>#include <stdbool.h>#define MAX 7int intArray[MAX] = {4,6,3,2,1,9,7};void printline(int count){int i;for(i = 0;i <count-1;i++){printf("=");}printf("=n");}void display(){int i;printf("[");// navigate through all itemsfor(i = 0;i<MAX;i++){printf("%d ", intArray[i]);}](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-161-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms153printf("]n");}void selectionSort(){int indexMin,i,j;// loop through all numbersfor(i = 0; i < MAX-1; i++){// set current element as minimumindexMin = i;// check the element to be minimumfor(j = i+1;j<MAX;j++){if(intArray[j] < intArray[indexMin]){indexMin = j;}}if(indexMin != i){printf("Items swapped: [ %d, %d ]n" , intArray[i],intArray[indexMin]);// swap the numbersint temp = intArray[indexMin];intArray[indexMin] = intArray[i];intArray[i] = temp;}printf("Iteration %d#:",(i+1));display();}}](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-162-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms154main(){printf("Input Array: ");display();printline(50);selectionSort();printf("Output Array: ");display();printline(50);}If we compile and run the above program, it will produce the following result −Input Array: [4 6 3 2 1 9 7 ]==================================================Items swapped: [ 4, 1 ]Iteration 1#:[1 6 3 2 4 9 7 ]Items swapped: [ 6, 2 ]Iteration 2#:[1 2 3 6 4 9 7 ]Iteration 3#:[1 2 3 6 4 9 7 ]Items swapped: [ 6, 4 ]Iteration 4#:[1 2 3 4 6 9 7 ]Iteration 5#:[1 2 3 4 6 9 7 ]Items swapped: [ 9, 7 ]Iteration 6#:[1 2 3 4 6 7 9 ]Output Array: [1 2 3 4 6 7 9 ]==================================================](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-163-2048.jpg&f=jpg&w=240)

![Data Structures & Algorithms156In the next iteration of the combining phase, we compare lists of two data values, andmerge them into a list of found data values placing all in a sorted order.After the final merging, the list should look like this −Now we should learn some programming aspects of merge sorting.AlgorithmMerge sort keeps on dividing the list into equal halves until it can no more be divided. Bydefinition, if it is only one element in the list, it is sorted. Then, merge sort combines thesmaller sorted lists keeping the new list sorted too.Step 1 − if it is only one element in the list it is already sorted, return.Step 2 − divide the list recursively into two halves until it can no more bedivided.Step 3 − merge the smaller lists into new list in sorted order.PseudocodeWe shall now see the pseudocodes for merge sort functions. As our algorithms point outtwo main functions − divide & merge.Merge sort works with recursion and we shall see our implementation in the same way.procedure mergesort( var a as array )if ( n == 1 ) return avar l1 as array = a[0] ... a[n/2]var l2 as array = a[n/2+1] ... a[n]l1 = mergesort( l1 )](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-165-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms157l2 = mergesort( l2 )return merge( l1, l2 )end procedureprocedure merge( var a as array, var b as array )var c as arraywhile ( a and b have elements )if ( a[0] > b[0] )add b[0] to the end of cremove b[0] from belseadd a[0] to the end of cremove a[0] from aend ifend whilewhile ( a has elements )add a[0] to the end of cremove a[0] from aend whilewhile ( b has elements )add b[0] to the end of cremove b[0] from bend whilereturn cend procedureTo know about merge sort implementation in C programming language, please click here.](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-166-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms158MergeSortPrograminCMerge sort is a sorting technique based on divide and conquer technique. With the worst-case time complexity being Ο(n log n), it is one of the most respected algorithms.Implementation in CWe shall see the implementation of merge sort in C programming language here −#include <stdio.h>#define max 10int a[10] = { 10, 14, 19, 26, 27, 31, 33, 35, 42, 44 };int b[10];void merging(int low, int mid, int high) {int l1, l2, i;for(l1 = low, l2 = mid + 1, i = low; l1 <= mid && l2 <= high; i++) {if(a[l1] <= a[l2])b[i] = a[l1++];elseb[i] = a[l2++];}while(l1 <= mid)b[i++] = a[l1++];while(l2 <= high)b[i++] = a[l2++];for(i = low; i <= high; i++)a[i] = b[i];}void sort(int low, int high) {int mid;if(low < high) {](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-167-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms159mid = (low + high) / 2;sort(low, mid);sort(mid+1, high);merging(low, mid, high);}else {return;}}int main() {int i;printf("List before sortingn");for(i = 0; i <= max; i++)printf("%d ", a[i]);sort(0, max);printf("nList after sortingn");for(i = 0; i <= max; i++)printf("%d ", a[i]);}If we compile and run the above program, it will produce the following result −List before sorting10 14 19 26 27 31 33 35 42 44 0List after sorting0 10 14 19 26 27 31 33 35 42 44](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-168-2048.jpg&f=jpg&w=240)



![Data Structures & Algorithms163We see that it required only four swaps to sort the rest of the array.AlgorithmFollowing is the algorithm for shell sort.Step 1 − Initialize the value of hStep 2 − Divide the list into smaller sub-list of equal interval hStep 3 − Sort these sub-lists using insertion sortStep 3 − Repeat until complete list is sortedPseudocodeFollowing is the pseudocode for shell sort.procedure shellSort()A : array of items/* calculate interval*/while interval < A.length /3 do:interval = interval * 3 + 1end whilewhile interval > 0 do:for outer = interval; outer < A.length; outer ++ do:/* select value to be inserted */valueToInsert = A[outer]inner = outer;/*shift element towards right*/while inner > interval -1 && A[inner - interval] >= valueToInsert do:A[inner] = A[inner - interval]inner = inner - intervalend while](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-172-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms164/* insert the number at hole position */A[inner] = valueToInsertend for/* calculate interval*/interval = (interval -1) /3;end whileend procedureTo know about shell sort implementation in C programming language, please click here.ShellSortPrograminCShell sort is a highly efficient sorting algorithm and is based on insertion sort algorithm.This algorithm avoids large shifts as in case of insertion sort, if the smaller value is to thefar right and has to be moved to the far left.Implementation in C#include <stdio.h>#include <stdbool.h>#define MAX 7int intArray[MAX] = {4,6,3,2,1,9,7};void printline(int count){int i;for(i = 0;i <count-1;i++){printf("=");}printf("=n");}](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-173-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms165void display(){int i;printf("[");// navigate through all itemsfor(i = 0;i<MAX;i++){printf("%d ",intArray[i]);}printf("]n");}void shellSort(){int inner, outer;int valueToInsert;int interval = 1;int elements = MAX;int i = 0;while(interval <= elements/3) {interval = interval*3 +1;}while(interval > 0) {printf("iteration %d#:",i);display();for(outer = interval; outer < elements; outer++) {valueToInsert = intArray[outer];inner = outer;while(inner > interval -1 && intArray[inner - interval]>= valueToInsert) {intArray[inner] = intArray[inner - interval];inner -=interval;printf(" item moved :%dn",intArray[inner]);}](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-174-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms166intArray[inner] = valueToInsert;printf(" item inserted :%d, at position :%dn",valueToInsert,inner);}interval = (interval -1) /3;i++;}}int main() {printf("Input Array: ");display();printline(50);shellSort();printf("Output Array: ");display();printline(50);return 1;}If we compile and run the above program, it will produce the following result −Input Array: [4 6 3 2 1 9 7 ]==================================================iteration 0#:[4 6 3 2 1 9 7 ]item moved :4item inserted :1, at position :0item inserted :9, at position :5item inserted :7, at position :6iteration 1#:[1 6 3 2 4 9 7 ]item inserted :6, at position :1item moved :6item inserted :3, at position :1item moved :6](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-175-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms167item moved :3item inserted :2, at position :1item moved :6item inserted :4, at position :3item inserted :9, at position :5item moved :9item inserted :7, at position :5Output Array: [1 2 3 4 6 7 9 ]==================================================](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-176-2048.jpg&f=jpg&w=240)

![Data Structures & Algorithms169QuickSortPivotPseudocodeThe pseudocode for the above algorithm can be derived as −function partitionFunc(left, right, pivot)leftPointer = left -1rightPointer = rightwhile True dowhile A[++leftPointer] < pivot do//do-nothingend whilewhile rightPointer > 0 && A[--rightPointer] > pivot do//do-nothingend whileif leftPointer >= rightPointerbreakelseswap leftPointer,rightPointerend ifend whileswap leftPointer,rightreturn leftPointerend functionQuickSortAlgorithmUsing pivot algorithm recursively, we end up with smaller possible partitions. Eachpartition is then processed for quick sort. We define recursive algorithm for quicksort asfollows −Step 1 − Make the right-most index value pivotStep 2 − partition the array using pivot valueStep 3 − quicksort left partition recursivelyStep 4 − quicksort right partition recursively](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-178-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms170QuickSortPseudocodeTo get more into it, let see the pseudocode for quick sort algorithm −procedure quickSort(left, right)if right-left <= 0returnelsepivot = A[right]partition = partitionFunc(left, right, pivot)quickSort(left,partition-1)quickSort(partition+1,right)end ifend procedureTo know about quick sort implementation in C programming language, please click here.QuickSortPrograminCQuick sort is a highly efficient sorting algorithm and is based on partitioning of array ofdata into smaller arrays. A large array is partitioned into two arrays one of which holdsvalues smaller than the specified value, say pivot, based on which the partition is madeand another array holds values greater than the pivot value.Implementation in C#include <stdio.h>#include <stdbool.h>#define MAX 7int intArray[MAX] = {4,6,3,2,1,9,7};void printline(int count){int i;for(i = 0;i <count-1;i++){printf("=");}](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-179-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms171printf("=n");}void display(){int i;printf("[");// navigate through all itemsfor(i = 0;i<MAX;i++){printf("%d ",intArray[i]);}printf("]n");}void swap(int num1, int num2){int temp = intArray[num1];intArray[num1] = intArray[num2];intArray[num2] = temp;}int partition(int left, int right, int pivot){int leftPointer = left -1;int rightPointer = right;while(true){while(intArray[++leftPointer] < pivot){//do nothing}while(rightPointer > 0 && intArray[--rightPointer] > pivot){//do nothing}if(leftPointer >= rightPointer){break;}else{](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-180-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms172printf(" item swapped :%d,%dn",intArray[leftPointer],intArray[rightPointer]);swap(leftPointer,rightPointer);}}printf(" pivot swapped :%d,%dn", intArray[leftPointer],intArray[right]);swap(leftPointer,right);printf("Updated Array: ");display();return leftPointer;}void quickSort(int left, int right){if(right-left <= 0){return;}else {int pivot = intArray[right];int partitionPoint = partition(left, right, pivot);quickSort(left,partitionPoint-1);quickSort(partitionPoint+1,right);}}main(){printf("Input Array: ");display();printline(50);quickSort(0,MAX-1);printf("Output Array: ");display();printline(50);}](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-181-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms173If we compile and run the above program, it will produce the following result −Input Array: [4 6 3 2 1 9 7 ]==================================================pivot swapped :9,7Updated Array: [4 6 3 2 1 7 9 ]pivot swapped :4,1Updated Array: [1 6 3 2 4 7 9 ]item swapped :6,2pivot swapped :6,4Updated Array: [1 2 3 4 6 7 9 ]pivot swapped :3,3Updated Array: [1 2 3 4 6 7 9 ]Output Array: [1 2 3 4 6 7 9 ]==================================================](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-182-2048.jpg&f=jpg&w=240)








![Data Structures & Algorithms182//stack variablesint stack[MAX];int top = -1;//graph variables//array of verticesstruct Vertex* lstVertices[MAX];//adjacency matrixint adjMatrix[MAX][MAX];//vertex countint vertexCount = 0;//stack functionsvoid push(int item) {stack[++top] = item;}int pop() {return stack[top--];}int peek() {return stack[top];}bool isStackEmpty() {return top == -1;}](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-191-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms183//graph functions//add vertex to the vertex listvoid addVertex(char label) {struct Vertex* vertex = (struct Vertex*) malloc(sizeof(struct Vertex));vertex->label = label;vertex->visited = false;lstVertices[vertexCount++] = vertex;}//add edge to edge arrayvoid addEdge(int start,int end) {adjMatrix[start][end] = 1;adjMatrix[end][start] = 1;}//display the vertexvoid displayVertex(int vertexIndex) {printf("%c ",lstVertices[vertexIndex]->label);}//get the adjacent unvisited vertexint getAdjUnvisitedVertex(int vertexIndex) {int i;for(i = 0; i<vertexCount; i++) {if(adjMatrix[vertexIndex][i] == 1 && lstVertices[i]->visited == false) {return i;}}return -1;}](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-192-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms184void depthFirstSearch() {int i;//mark first node as visitedlstVertices[0]->visited = true;//display the vertexdisplayVertex(0);//push vertex index in stackpush(0);while(!isStackEmpty()) {//get the unvisited vertex of vertex which is at top of the stackint unvisitedVertex = getAdjUnvisitedVertex(peek());//no adjacent vertex foundif(unvisitedVertex == -1) {pop();}else {lstVertices[unvisitedVertex]->visited = true;displayVertex(unvisitedVertex);push(unvisitedVertex);}}//stack is empty, search is complete, reset the visited flagfor(i = 0;i < vertexCount;i++) {lstVertices[i]->visited = false;}}](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-193-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms185int main() {int i, j;for(i = 0; i<MAX; i++) // set adjacency {for(j = 0; j<MAX; j++) // matrix to 0adjMatrix[i][j] = 0;}addVertex('S'); // 0addVertex('A'); // 1addVertex('B'); // 2addVertex('C'); // 3addVertex('D'); // 4addEdge(0, 1); // S - AaddEdge(0, 2); // S - BaddEdge(0, 3); // S - CaddEdge(1, 4); // A - DaddEdge(2, 4); // B - DaddEdge(3, 4); // C - Dprintf("Depth First Search: ");depthFirstSearch();return 0;}If we compile and run the above program, it will produce the following result −Depth First Search: S A D B C](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-194-2048.jpg&f=jpg&w=240)



![Data Structures & Algorithms189Implementation in C#include <stdio.h>#include <stdlib.h>#include <stdbool.h>#define MAX 5struct Vertex {char label;bool visited;};//queue variablesint queue[MAX];int rear = -1;int front = 0;int queueItemCount = 0;//graph variables](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-198-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms190//array of verticesstruct Vertex* lstVertices[MAX];//adjacency matrixint adjMatrix[MAX][MAX];//vertex countint vertexCount = 0;//queue functionsvoid insert(int data) {queue[++rear] = data;queueItemCount++;}int removeData() {queueItemCount--;return queue[front++];}bool isQueueEmpty() {return queueItemCount == 0;}//graph functions//add vertex to the vertex listvoid addVertex(char label) {struct Vertex* vertex = (struct Vertex*) malloc(sizeof(struct Vertex));vertex->label = label;vertex->visited = false;lstVertices[vertexCount++] = vertex;}](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-199-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms191//add edge to edge arrayvoid addEdge(int start,int end) {adjMatrix[start][end] = 1;adjMatrix[end][start] = 1;}//display the vertexvoid displayVertex(int vertexIndex) {printf("%c ",lstVertices[vertexIndex]->label);}//get the adjacent unvisited vertexint getAdjUnvisitedVertex(int vertexIndex) {int i;for(i = 0; i<vertexCount; i++) {if(adjMatrix[vertexIndex][i] == 1 && lstVertices[i]->visited == false)return i;}return -1;}void breadthFirstSearch() {int i;//mark first node as visitedlstVertices[0]->visited = true;//display the vertexdisplayVertex(0);](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-200-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms192//insert vertex index in queueinsert(0);int unvisitedVertex;while(!isQueueEmpty()) {//get the unvisited vertex of vertex which is at front of the queueint tempVertex = removeData();//no adjacent vertex foundwhile((unvisitedVertex = getAdjUnvisitedVertex(tempVertex)) != -1) {lstVertices[unvisitedVertex]->visited = true;displayVertex(unvisitedVertex);insert(unvisitedVertex);}}//queue is empty, search is complete, reset the visited flagfor(i = 0;i<vertexCount;i++) {lstVertices[i]->visited = false;}}int main() {int i, j;for(i = 0; i<MAX; i++) // set adjacency {for(j = 0; j<MAX; j++) // matrix to 0adjMatrix[i][j] = 0;}addVertex('S'); // 0addVertex('A'); // 1addVertex('B'); // 2addVertex('C'); // 3addVertex('D'); // 4](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-201-2048.jpg&f=jpg&w=240)











![Data Structures & Algorithms204}}void post_order_traversal(struct node* root) {if(root != NULL) {post_order_traversal(root->leftChild);post_order_traversal(root->rightChild);printf("%d ", root->data);}}int main() {int i;int array[7] = { 27, 14, 35, 10, 19, 31, 42 };for(i = 0; i < 7; i++)insert(array[i]);i = 31;struct node * temp = search(i);if(temp != NULL) {printf("[%d] Element found.", temp->data);printf("n");}else {printf("[ x ] Element not found (%d).n", i);}i = 15;temp = search(i);if(temp != NULL) {printf("[%d] Element found.", temp->data);printf("n");}else {printf("[ x ] Element not found (%d).n", i);}](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-213-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms205printf("nPreorder traversal: ");pre_order_traversal(root);printf("nInorder traversal: ");inorder_traversal(root);printf("nPost order traversal: ");post_order_traversal(root);return 0;}If we compile and run the above program, it will produce the following result −Visiting elements: 27 35 [31] Element found.Visiting elements: 27 14 19 [ x ] Element not found (15).Preorder traversal: 27 14 10 19 35 31 42Inorder traversal: 10 14 19 27 31 35 42Post order traversal: 10 19 14 31 42 35 27](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-214-2048.jpg&f=jpg&w=240)







![Data Structures & Algorithms213int i;int array[7] = { 27, 14, 35, 10, 19, 31, 42 };for(i = 0; i < 7; i++)insert(array[i]);i = 31;struct node * temp = search(i);if(temp != NULL) {printf("[%d] Element found.", temp->data);printf("n");}else {printf("[ x ] Element not found (%d).n", i);}i = 15;temp = search(i);if(temp != NULL) {printf("[%d] Element found.", temp->data);printf("n");}else {printf("[ x ] Element not found (%d).n", i);}printf("nPreorder traversal: ");pre_order_traversal(root);printf("nInorder traversal: ");inorder_traversal(root);printf("nPost order traversal: ");post_order_traversal(root);return 0;}](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-222-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms214If we compile and run the above program, it will produce the following result −Visiting elements: 27 35 [31] Element found.Visiting elements: 27 14 19 [ x ] Element not found (15).Preorder traversal: 27 14 10 19 35 31 42Inorder traversal: 10 14 19 27 31 35 42Post order traversal: 10 19 14 31 42 35 27](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-223-2048.jpg&f=jpg&w=240)
































![Data Structures & Algorithms247TowerofHanoiinCProgram#include <stdio.h>#include <stdbool.h>#define MAX 10int list[MAX] = {1,8,4,6,0,3,5,2,7,9};void display(){int i;printf("[");// navigate through all itemsfor(i = 0; i < MAX; i++){printf("%d ",list[i]);}printf("]n");}void bubbleSort() {int temp;int i,j;bool swapped = false;// loop through all numbersfor(i = 0; i < MAX-1; i++) {swapped = false;// loop through numbers falling aheadfor(j = 0; j < MAX-1-i; j++) {printf("Items compared: [ %d, %d ] ", list[j],list[j+1]);](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-256-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms248// check if next number is lesser than current no// swap the numbers.// (Bubble up the highest number)if(list[j] > list[j+1]) {temp = list[j];list[j] = list[j+1];list[j+1] = temp;swapped = true;printf(" => swapped [%d, %d]n",list[j],list[j+1]);}else {printf(" => not swappedn");}}// if no number was swapped that means// array is sorted now, break the loop.if(!swapped) {break;}printf("Iteration %d#: ",(i+1));display();}}main(){printf("Input Array: ");display();printf("n");bubbleSort();printf("nOutput Array: ");display();}](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-257-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms249If we compile and run the above program, it will produce the following result −Input Array: [1 8 4 6 0 3 5 2 7 9 ]Items compared: [ 1, 8 ] => not swappedItems compared: [ 8, 4 ] => swapped [4, 8]Items compared: [ 8, 6 ] => swapped [6, 8]Items compared: [ 8, 0 ] => swapped [0, 8]Items compared: [ 8, 3 ] => swapped [3, 8]Items compared: [ 8, 5 ] => swapped [5, 8]Items compared: [ 8, 2 ] => swapped [2, 8]Items compared: [ 8, 7 ] => swapped [7, 8]Items compared: [ 8, 9 ] => not swappedIteration 1#: [1 4 6 0 3 5 2 7 8 9 ]Items compared: [ 1, 4 ] => not swappedItems compared: [ 4, 6 ] => not swappedItems compared: [ 6, 0 ] => swapped [0, 6]Items compared: [ 6, 3 ] => swapped [3, 6]Items compared: [ 6, 5 ] => swapped [5, 6]Items compared: [ 6, 2 ] => swapped [2, 6]Items compared: [ 6, 7 ] => not swappedItems compared: [ 7, 8 ] => not swappedIteration 2#: [1 4 0 3 5 2 6 7 8 9 ]Items compared: [ 1, 4 ] => not swappedItems compared: [ 4, 0 ] => swapped [0, 4]Items compared: [ 4, 3 ] => swapped [3, 4]Items compared: [ 4, 5 ] => not swappedItems compared: [ 5, 2 ] => swapped [2, 5]Items compared: [ 5, 6 ] => not swappedItems compared: [ 6, 7 ] => not swappedIteration 3#: [1 0 3 4 2 5 6 7 8 9 ]Items compared: [ 1, 0 ] => swapped [0, 1]Items compared: [ 1, 3 ] => not swappedItems compared: [ 3, 4 ] => not swappedItems compared: [ 4, 2 ] => swapped [2, 4]Items compared: [ 4, 5 ] => not swappedItems compared: [ 5, 6 ] => not swapped](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-258-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms250Iteration 4#: [0 1 3 2 4 5 6 7 8 9 ]Items compared: [ 0, 1 ] => not swappedItems compared: [ 1, 3 ] => not swappedItems compared: [ 3, 2 ] => swapped [2, 3]Items compared: [ 3, 4 ] => not swappedItems compared: [ 4, 5 ] => not swappedIteration 5#: [0 1 2 3 4 5 6 7 8 9 ]Items compared: [ 0, 1 ] => not swappedItems compared: [ 1, 2 ] => not swappedItems compared: [ 2, 3 ] => not swappedItems compared: [ 3, 4 ] => not swappedOutput Array: [0 1 2 3 4 5 6 7 8 9 ]](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-259-2048.jpg&f=jpg&w=240)






This document provides an overview and introduction to data structures and algorithms. It discusses the need for data structures to efficiently organize and store data as applications and data grow increasingly large and complex. It also covers some basic terminology used in data structures and algorithms. The document then discusses setting up both an online and local environment for writing and executing code in C programming language to work through examples.


































![Data Structures & Algorithms26ExampleResultLet LA be a Linear Array (unordered) with N elements and K is a positive integer suchthat K<=N. Following is the algorithm where ITEM is inserted into the Kthposition of LA −1. Start2. Set J=N3. Set N = N+14. Repeat steps 5 and 6 while J >= K5. Set LA[J+1] = LA[J]6. Set J = J-17. Set LA[K] = ITEM8. StopExampleFollowing is the implementation of the above algorithm −#include <stdio.h>main() {int LA[] = {1,3,5,7,8};int item = 10, k = 3, n = 5;int i = 0, j = n;printf("The original array elements are :n");for(i = 0; i<n; i++) {printf("LA[%d] = %d n", i, LA[i]);}n = n + 1;while( j >= k){LA[j+1] = LA[j];j = j - 1;}](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-35-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms27LA[k] = item;printf("The array elements after insertion :n");for(i = 0; i<n; i++) {printf("LA[%d] = %d n", i, LA[i]);}}When we compile and execute the above program, it produces the following result −The original array elements are :LA[0]=1LA[1]=3LA[2]=5LA[3]=7LA[4]=8The array elements after insertion :LA[0]=1LA[1]=3LA[2]=5LA[3]=10LA[4]=7LA[5]=8For other variations of array insertion operation click hereArrayInsertionsIn the previous section, we have learnt how the insertion operation works. It is not alwaysnecessary that an element is inserted at the end of an array. Following can be a situationwith array insertion − Insertion at the beginning of an array Insertion at the given index of an array Insertion after the given index of an array Insertion before the given index of an array](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-36-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms28InsertionattheBeginningofanArrayWhen the insertion happens at the beginning, it causes all the existing data items to shiftone step downward. Here, we design and implement an algorithm to insert an element atthe beginning of an array.AlgorithmWe assume A is an array with N elements. The maximum numbers of elements it canstore is defined by MAX. We shall first check if an array has any empty space to store anyelement and then we proceed with the insertion process.beginIF N = MAX, returnELSEN = N + 1For All Elements in AMove to next adjacent locationA[FIRST] = New_ElementendImplementation in C#include <stdio.h>#define MAX 5void main() {int array[MAX] = {2, 3, 4, 5};int N = 4; // number of elements in arrayint i = 0; // loop variableint value = 1; // new data element to be stored in array// print array before insertionprintf("Printing array before insertion −n");](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-37-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms29for(i = 0; i < N; i++) {printf("array[%d] = %d n", i, array[i]);}// now shift rest of the elements downwardsfor(i = N; i >= 0; i--) {array[i+1] = array[i];}// add new element at first positionarray[0] = value;// increase N to reflect number of elementsN++;// print to confirmprintf("Printing array after insertion −n");for(i = 0; i < N; i++) {printf("array[%d] = %dn", i, array[i]);}}This program should yield the following output −Printing array before insertion −array[0] = 2array[1] = 3array[2] = 4array[3] = 5Printing array after insertion −array[0] = 0array[1] = 2array[2] = 3array[3] = 4array[4] = 5](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-38-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms30InsertionattheGivenIndexofanArrayIn this scenario, we are given the exact location (index) of an array where a new dataelement (value) needs to be inserted. First we shall check if the array is full, if it is not,then we shall move all data elements from that location one step downward. This will makeroom for a new data element.AlgorithmWe assume A is an array with N elements. The maximum numbers of elements it canstore is defined by MAX.beginIF N = MAX, returnELSEN = N + 1SEEK Location indexFor All Elements from A[index] to A[N]Move to next adjacent locationA[index] = New_ElementendImplementation in C#include <stdio.h>#define MAX 5void main() {int array[MAX] = {1, 2, 4, 5};int N = 4; // number of elements in arrayint i = 0; // loop variableint index = 2; // index location to insert new valueint value = 3; // new data element to be inserted// print array before insertionprintf("Printing array before insertion −n");](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-39-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms31for(i = 0; i < N; i++) {printf("array[%d] = %d n", i, array[i]);}// now shift rest of the elements downwardsfor(i = N; i >= index; i--) {array[i+1] = array[i];}// add new element at first positionarray[index] = value;// increase N to reflect number of elementsN++;// print to confirmprintf("Printing array after insertion −n");for(i = 0; i < N; i++) {printf("array[%d] = %dn", i, array[i]);}}If we compile and run the above program, it will produce the following result −Printing array before insertion −array[0] = 1array[1] = 2array[2] = 4array[3] = 5Printing array after insertion −array[0] = 1array[1] = 2array[2] = 3array[3] = 4array[4] = 5](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-40-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms32InsertionAftertheGivenIndexofanArrayIn this scenario we are given a location (index) of an array after which a new data element(value) has to be inserted. Only the seek process varies, the rest of the activities are thesame as in the previous example.AlgorithmWe assume A is an array with N elements. The maximum numbers of elements it canstore is defined by MAX.beginIF N = MAX, returnELSEN = N + 1SEEK Location indexFor All Elements from A[index + 1] to A[N]Move to next adjacent locationA[index + 1] = New_ElementendImplementation in C#include <stdio.h>#define MAX 5void main() {int array[MAX] = {1, 2, 4, 5};int N = 4; // number of elements in arrayint i = 0; // loop variableint index = 1; // index location after which value will be insertedint value = 3; // new data element to be inserted// print array before insertionprintf("Printing array before insertion −n");](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-41-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms33for(i = 0; i < N; i++) {printf("array[%d] = %d n", i, array[i]);}// now shift rest of the elements downwardsfor(i = N; i >= index + 1; i--) {array[i + 1] = array[i];}// add new element at first positionarray[index + 1] = value;// increase N to reflect number of elementsN++;// print to confirmprintf("Printing array after insertion −n");for(i = 0; i < N; i++) {printf("array[%d] = %dn", i, array[i]);}}If we compile and run the above program, it will produce the following result −Printing array before insertion −array[0] = 1array[1] = 2array[2] = 4array[3] = 5Printing array after insertion −array[0] = 1array[1] = 2array[2] = 3array[3] = 4](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-42-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms34array[4] = 5InsertionBeforetheGivenIndexofanArrayIn this scenario we are given a location (index) of an array before which a new dataelement (value) has to be inserted. This time we seek till index-1, i.e., one locationahead of the given index. Rest of the activities are the same as in the previous example.AlgorithmWe assume A is an array with N elements. The maximum numbers of elements it canstore is defined by MAX.beginIF N = MAX, returnELSEN = N + 1SEEK Location indexFor All Elements from A[index - 1] to A[N]Move to next adjacent locationA[index - 1] = New_ElementendImplementation in C#include <stdio.h>#define MAX 5](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-43-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms35void main() {int array[MAX] = {1, 2, 4, 5};int N = 4; // number of elements in arrayint i = 0; // loop variableint index = 3; // index location before which value will be insertedint value = 3; // new data element to be inserted// print array before insertionprintf("Printing array before insertion −n");for(i = 0; i < N; i++) {printf("array[%d] = %d n", i, array[i]);}// now shift rest of the elements downwardsfor(i = N; i >= index + 1; i--) {array[i + 1] = array[i];}// add new element at first positionarray[index + 1] = value;// increase N to reflect number of elementsN++;// print to confirmprintf("Printing array after insertion −n");for(i = 0; i < N; i++) {printf("array[%d] = %dn", i, array[i]);}}If we compile and run the above program, it will produce the following result −Printing array before insertion −array[0] = 1array[1] = 2](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-44-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms36array[2] = 4array[3] = 5Printing array after insertion −array[0] = 1array[1] = 2array[2] = 4array[3] = 5array[4] = 3DeletionOperationDeletion refers to removing an existing element from the array and re-organizing allelements of an array.AlgorithmConsider LA is a linear array with N elements and K is a positive integer such that K<=N.Following is the algorithm to delete an element available at the Kthposition of LA.1. Start2. Set J=K3. Repeat steps 4 and 5 while J < N4. Set LA[J-1] = LA[J]5. Set J = J+16. Set N = N-17. StopExampleFollowing is the implementation of the above algorithm −#include <stdio.h>main() {int LA[] = {1,3,5,7,8};int k = 3, n = 5;int i, j;printf("The original array elements are :n");](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-45-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms37for(i = 0; i<n; i++) {printf("LA[%d] = %d n", i, LA[i]);}j = k;while( j < n){LA[j-1] = LA[j];j = j + 1;}n = n -1;printf("The array elements after deletion :n");for(i = 0; i<n; i++) {printf("LA[%d] = %d n", i, LA[i]);}}When we compile and execute the above program, it produces the following result −The original array elements are :LA[0]=1LA[1]=3LA[2]=5LA[3]=7LA[4]=8The array elements after deletion :LA[0]=1LA[1]=3LA[2]=7LA[3]=8SearchOperationYou can perform a search for an array element based on its value or its index.Algorithm](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-46-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms38Consider LA is a linear array with N elements and K is a positive integer such that K<=N.Following is the algorithm to find an element with a value of ITEM using sequential search.1. Start2. Set J=03. Repeat steps 4 and 5 while J < N4. IF LA[J] is equal ITEM THEN GOTO STEP 65. Set J = J +16. PRINT J, ITEM7. StopExampleFollowing is the implementation of the above algorithm −#include <stdio.h>main() {int LA[] = {1,3,5,7,8};int item = 5, n = 5;int i = 0, j = 0;printf("The original array elements are :n");for(i = 0; i<n; i++) {printf("LA[%d] = %d n", i, LA[i]);}while( j < n){if( LA[j] == item ){break;}j = j + 1;}printf("Found element %d at position %dn", item, j+1);}When we compile and execute the above program, it produces the following result −](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-47-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms39The original array elements are :LA[0]=1LA[1]=3LA[2]=5LA[3]=7LA[4]=8Found element 5 at position 3UpdateOperationUpdate operation refers to updating an existing element from the array at a given index.AlgorithmConsider LA is a linear array with N elements and K is a positive integer such that K<=N.Following is the algorithm to update an element available at the Kthposition of LA.1. Start2. Set LA[K-1] = ITEM3. StopExampleFollowing is the implementation of the above algorithm −#include <stdio.h>main() {int LA[] = {1,3,5,7,8};int k = 3, n = 5, item = 10;int i, j;printf("The original array elements are :n");for(i = 0; i<n; i++) {printf("LA[%d] = %d n", i, LA[i]);}LA[k-1] = item;printf("The array elements after updation :n");](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-48-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms40for(i = 0; i<n; i++) {printf("LA[%d] = %d n", i, LA[i]);}}When we compile and execute the above program, it produces the following result −The original array elements are :LA[0]=1LA[1]=3LA[2]=5LA[3]=7LA[4]=8The array elements after updation :LA[0]=1LA[1]=3LA[2]=10LA[3]=7LA[4]=8](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-49-2048.jpg&f=jpg&w=240)






![Data Structures & Algorithms47Implementation in C#include <stdio.h>#include <string.h>#include <stdlib.h>#include <stdbool.h>struct node{int data;int key;struct node *next;};struct node *head = NULL;struct node *current = NULL;//display the listvoid printList(){struct node *ptr = head;printf("n[ ");//start from the beginningwhile(ptr != NULL){printf("(%d,%d) ",ptr->key,ptr->data);ptr = ptr->next;}printf(" ]");}//insert link at the first locationvoid insertFirst(int key, int data){//create a link](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-56-2048.jpg&f=jpg&w=240)






![Data Structures & Algorithms54printf("nList after reversing the data: ");printList();}If we compile and run the above program, it will produce the following result −Original List:[ (6,56) (5,40) (4,1) (3,30) (2,20) (1,10) ]Deleted value:(6,56)Deleted value:(5,40)Deleted value:(4,1)Deleted value:(3,30)Deleted value:(2,20)Deleted value:(1,10)List after deleting all items:[ ]Restored List:[ (6,56) (5,40) (4,1) (3,30) (2,20) (1,10) ]Element found: (4,1)List after deleting an item:[ (6,56) (5,40) (3,30) (2,20) (1,10) ]Element not found.List after sorting the data:[ (1,10) (2,20) (3,30) (5,40) (6,56) ]List after reversing the data:[ (6,56) (5,40) (3,30) (2,20) (1,10) ]](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-63-2048.jpg&f=jpg&w=240)





![Data Structures & Algorithms60printf(" ]");}//display the list from last to firstvoid displayBackward(){//start from the laststruct node *ptr = last;//navigate till the start of the listprintf("n[ ");while(ptr != NULL){//print dataprintf("(%d,%d) ",ptr->key,ptr->data);//move to next itemptr = ptr ->prev;printf(" ");}printf(" ]");}//insert link at the first locationvoid insertFirst(int key, int data){//create a linkstruct node *link = (struct node*) malloc(sizeof(struct node));link->key = key;link->data = data;if(isEmpty()){//make it the last linklast = link;](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-69-2048.jpg&f=jpg&w=240)





![Data Structures & Algorithms66deleteLast();displayForward();printf("nList , insert after key(4) : ");insertAfter(4,7, 13);displayForward();printf("nList , after delete key(4) : ");delete(4);displayForward();}If we compile and run the above program, it will produce the following result −List (First to Last):[ (6,56) (5,40) (4,1) (3,30) (2,20) (1,10) ]List (Last to first):[ (1,10) (2,20) (3,30) (4,1) (5,40) (6,56) ]List , after deleting first record:[ (5,40) (4,1) (3,30) (2,20) (1,10) ]List , after deleting last record:[ (5,40) (4,1) (3,30) (2,20) ]List , insert after key(4) :[ (5,40) (4,1) (4,13) (3,30) (2,20) ]List , after delete key(4) :[ (5,40) (4,13) (3,30) (2,20) ]](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-75-2048.jpg&f=jpg&w=240)


![Data Structures & Algorithms69//mark next to first link as firsthead = head->next;//return the deleted linkreturn tempLink;}DisplayListOperationFollowing code demonstrates the display list operation in a circular linked list.//display the listvoid printList() {struct node *ptr = head;printf("n[ ");//start from the beginningif(head != NULL) {while(ptr->next != ptr) {printf("(%d,%d) ",ptr->key,ptr->data);ptr = ptr->next;}}printf(" ]");}To know about its implementation in C programming language, please click here.CircularLinkedListPrograminCCircular Linked List is a variation of Linked list in which the first element points to the lastelement and the last element points to the first element. Both Singly Linked List andDoubly Linked List can be made into a circular linked list.](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-78-2048.jpg&f=jpg&w=240)


![Data Structures & Algorithms72//mark next to first link as firsthead = head->next;//return the deleted linkreturn tempLink;}//display the listvoid printList(){struct node *ptr = head;printf("n[ ");//start from the beginningif(head != NULL){while(ptr->next != ptr){printf("(%d,%d) ",ptr->key,ptr->data);ptr = ptr->next;}}printf(" ]");}main() {insertFirst(1,10);insertFirst(2,20);insertFirst(3,30);insertFirst(4,1);insertFirst(5,40);insertFirst(6,56);](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-81-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms73printf("Original List: ");//print listprintList();while(!isEmpty()){struct node *temp = deleteFirst();printf("nDeleted value:");printf("(%d,%d) ",temp->key,temp->data);}printf("nList after deleting all items: ");printList();}If we compile and run the above program, it will produce the following result −Original List:[ (6,56) (5,40) (4,1) (3,30) (2,20) ]Deleted value:(6,56)Deleted value:(5,40)Deleted value:(4,1)Deleted value:(3,30)Deleted value:(2,20)Deleted value:(1,10)List after deleting all items:[ ]](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-82-2048.jpg&f=jpg&w=240)


![Data Structures & Algorithms76BasicOperationsStack operations may involve initializing the stack, using it and then de-initializing it. Apartfrom these basic stuffs, a stack is used for the following two primary operations − push() − Pushing (storing) an element on the stack. pop() − Removing (accessing) an element from the stack.When data is PUSHed onto stack.To use a stack efficiently, we need to check the status of stack as well. For the samepurpose, the following functionality is added to stacks − peek() − get the top data element of the stack, without removing it. isFull() − check if stack is full. isEmpty() − check if stack is empty.At all times, we maintain a pointer to the last PUSHed data on the stack. As this pointeralways represents the top of the stack, hence named top. The top pointer provides topvalue of the stack without actually removing it.First we should learn about procedures to support stack functions −peek()Algorithm of peek() function −begin procedure peekreturn stack[top]end procedureImplementation of peek() function in C programming language −int peek() {return stack[top];}](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-85-2048.jpg&f=jpg&w=240)


![Data Structures & Algorithms79If the linked list is used to implement the stack, then in step 3, we need to allocate spacedynamically.Algorithm for PUSH OperationA simple algorithm for Push operation can be derived as follows −begin procedure push: stack, dataif stack is fullreturn nullendiftop ← top + 1stack[top] ← dataend procedureImplementation of this algorithm in C, is very easy. See the following code −void push(int data) {if(!isFull()) {top = top + 1;stack[top] = data;}else {printf("Could not insert data, Stack is full.n");}}PopOperationAccessing the content while removing it from the stack, is known as a Pop Operation. Inan array implementation of pop() operation, the data element is not actually removed,instead top is decremented to a lower position in the stack to point to the next value. Butin linked-list implementation, pop() actually removes data element and deallocatesmemory space.A Pop operation may involve the following steps − Step 1 − Checks if the stack is empty. Step 2 − If the stack is empty, produces an error and exit.](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-88-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms80 Step 3 − If the stack is not empty, accesses the data element at which top ispointing. Step 4 − Decreases the value of top by 1. Step 5 − Returns success.Algorithm for Pop OperationA simple algorithm for Pop operation can be derived as follows −begin procedure pop: stackif stack is emptyreturn nullendifdata ← stack[top]top ← top - 1return dataend procedure](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-89-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms81Implementation of this algorithm in C, is as follows −int pop(int data) {if(!isempty()) {data = stack[top];top = top - 1;return data;}else {printf("Could not retrieve data, Stack is empty.n");}}For a complete stack program in C programming language, please click here.StackPrograminCWe shall see the stack implementation in C programming language here. You can try theprogram by clicking on the Try-it button. To learn the theory aspect of stacks, click on visitprevious page.Implementation in C#include <stdio.h>int MAXSIZE = 8;int stack[8];int top = -1;int isempty() {if(top == -1)return 1;elsereturn 0;}](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-90-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms82int isfull() {if(top == MAXSIZE)return 1;elsereturn 0;}int peek() {return stack[top];}int pop() {int data;if(!isempty()) {data = stack[top];top = top - 1;return data;}else {printf("Could not retrieve data, Stack is empty.n");}}int push(int data) {if(!isfull()) {top = top + 1;stack[top] = data;}else {printf("Could not insert data, Stack is full.n");}}](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-91-2048.jpg&f=jpg&w=240)




![Data Structures & Algorithms87In a+b*c, the expression part b*c will be evaluated first, with multiplication asprecedence over addition. We here use parenthesis for a+b to be evaluated first,like (a+b)*c.PostfixEvaluationAlgorithmWe shall now look at the algorithm on how to evaluate postfix notation −Step 1 − scan the expression from left to rightStep 2 − if it is an operand push it to stackStep 3 − if it is an operator pull operand from stack and perform operationStep 4 − store the output of step 3, back to stackStep 5 − scan the expression until all operands are consumedStep 6 − pop the stack and perform operationTo see the implementation in C programming language, please click hereExpressionParsingUsingStackInfix notation is easier for humans to read and understand whereas for electronic machineslike computers, postfix is the best form of expression to parse. We shall see here a programto convert and evaluate infix notation to postfix notation −#include<stdio.h>#include<string.h>//char stackchar stack[25];int top = -1;void push(char item) {stack[++top] = item;}char pop() {return stack[top--];}](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-96-2048.jpg&f=jpg&w=240)

![Data Structures & Algorithms89default:return 0;}}//converts infix expression to postfixvoid convert(char infix[],char postfix[]) {int i,symbol,j = 0;stack[++top] = '#';for(i = 0;i<strlen(infix);i++) {symbol = infix[i];if(isOperator(symbol) == 0) {postfix[j] = symbol;j++;} else {if(symbol == '(') {push(symbol);}else {if(symbol == ')') {while(stack[top] != '(') {postfix[j] = pop();j++;}pop();//pop out (.} else {if(precedence(symbol)>precedence(stack[top])) {push(symbol);}else {while(precedence(symbol)<=precedence(stack[top])) {postfix[j] = pop();j++;}](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-98-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms90push(symbol);}}}}}while(stack[top] != '#') {postfix[j] = pop();j++;}postfix[j]='0';//null terminate string.}//int stackint stack_int[25];int top_int = -1;void push_int(int item) {stack_int[++top_int] = item;}char pop_int() {return stack_int[top_int--];}//evaluates postfix expressionint evaluate(char *postfix){char ch;int i = 0,operand1,operand2;while( (ch = postfix[i++]) != '0') {if(isdigit(ch)) {](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-99-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms91push_int(ch-'0'); // Push the operand}else {//Operator,pop two operandsoperand2 = pop_int();operand1 = pop_int();switch(ch) {case '+':push_int(operand1+operand2);break;case '-':push_int(operand1-operand2);break;case '*':push_int(operand1*operand2);break;case '/':push_int(operand1/operand2);break;}}}return stack_int[top_int];}void main() {char infix[25] = "1*(2+3)",postfix[25];convert(infix,postfix);printf("Infix expression is: %sn" , infix);printf("Postfix expression is: %sn" , postfix);printf("Evaluated expression is: %dn" , evaluate(postfix));}](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-100-2048.jpg&f=jpg&w=240)


![Data Structures & Algorithms94Few more functions are required to make the above-mentioned queue operation efficient.These are − peek() − Gets the element at the front of the queue without removing it. isfull() − Checks if the queue is full. isempty() − Checks if the queue is empty.In queue, we always dequeue (or access) data, pointed by front pointer and whileenqueing (or storing) data in the queue we take help of rear pointer.Let's first learn about supportive functions of a queue −peek()This function helps to see the data at the front of the queue. The algorithm of peek()function is as follows −begin procedure peekreturn queue[front]end procedureImplementation of peek() function in C programming language −int peek() {return queue[front];}isfull()As we are using single dimension array to implement queue, we just check for the rearpointer to reach at MAXSIZE to determine that the queue is full. In case we maintain thequeue in a circular linked-list, the algorithm will differ. Algorithm of isfull() function −begin procedure isfullif rear equals to MAXSIZEreturn trueelse](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-103-2048.jpg&f=jpg&w=240)


![Data Structures & Algorithms97Algorithm for enqueue Operationprocedure enqueue(data)if queue is fullreturn overflowendifrear ← rear + 1queue[rear] ← datareturn trueend procedureImplementation of enqueue() in C programming language −int enqueue(int data)if(isfull())return 0;rear = rear + 1;queue[rear] = data;return 1;end procedureDequeueOperationAccessing data from the queue is a process of two tasks − access the data where front ispointing and remove the data after access. The following steps are taken toperform dequeue operation − Step 1 − Check if the queue is empty. Step 2 − If the queue is empty, produce underflow error and exit. Step 3 − If the queue is not empty, access the data where front is pointing. Step 4 − Increment front pointer to point to the next available data element. Step 5 − Return success.](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-106-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms98Algorithm for dequeue Operationprocedure dequeueif queue is emptyreturn underflowend ifdata = queue[front]front ← front + 1return trueend procedureImplementation of dequeue() in C programming language −int dequeue() {if(isempty())return 0;int data = queue[front];front = front + 1;return data;}For a complete Queue program in C programming language, please click here.](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-107-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms99QueuePrograminCWe shall see the stack implementation in C programming language here. You can try theprogram by clicking on the Try-it button. To learn the theory aspect of stacks, click on visitprevious page.Implementation in C#include <stdio.h>#include <string.h>#include <stdlib.h>#include <stdbool.h>#define MAX 6int intArray[MAX];int front = 0;int rear = -1;int itemCount = 0;int peek(){return intArray[front];}bool isEmpty(){return itemCount == 0;}bool isFull(){return itemCount == MAX;}int size(){return itemCount;}void insert(int data){if(!isFull()){](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-108-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms100if(rear == MAX-1){rear = -1;}intArray[++rear] = data;itemCount++;}}int removeData(){int data = intArray[front++];if(front == MAX){front = 0;}itemCount--;return data;}int main() {/* insert 5 items */insert(3);insert(5);insert(9);insert(1);insert(12);// front : 0// rear : 4// ------------------// index : 0 1 2 3 4// ------------------// queue : 3 5 9 1 12insert(15);// front : 0// rear : 5](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-109-2048.jpg&f=jpg&w=240)



![Data Structures & Algorithms104Linear search is a very simple search algorithm. In this type of search, a sequential searchis made over all items one by one. Every item is checked and if a match is found then thatparticular item is returned, otherwise the search continues till the end of the datacollection.AlgorithmLinear Search ( Array A, Value x)Step 1: Set i to 1Step 2: if i > n then go to step 7Step 3: if A[i] = x then go to step 6Step 4: Set i to i + 1Step 5: Go to Step 2Step 6: Print Element x Found at index i and go to step 8Step 7: Print element not foundStep 8: ExitPseudocodeprocedure linear_search (list, value)for each item in the listif match item == valuereturn the item's location16. Linear Search](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-113-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms105end ifend forend procedureTo know about linear search implementation in C programming language, please click-here.LinearSearchPrograminCHere we present the implementation of linear search in C programming language. Theoutput of the program is given after the code.Linear Search Program#include <stdio.h>#define MAX 20// array of items on which linear search will be conducted.int intArray[MAX] = {1,2,3,4,6,7,9,11,12,14,15,16,17,19,33,34,43,45,55,66};void printline(int count){int i;for(i = 0;i <count-1;i++){printf("=");}printf("=n");}// this method makes a linear search.int find(int data){int comparisons = 0;int index = -1;int i;](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-114-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms106// navigate through all itemsfor(i = 0;i<MAX;i++){// count the comparisons madecomparisons++;// if data found, break the loopif(data == intArray[i]){index = i;break;}}printf("Total comparisons made: %d", comparisons);return index;}void display(){int i;printf("[");// navigate through all itemsfor(i = 0;i<MAX;i++){printf("%d ",intArray[i]);}printf("]n");}main(){printf("Input Array: ");display();printline(50);](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-115-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms107//find location of 1int location = find(55);// if element was foundif(location != -1)printf("nElement found at location: %d" ,(location+1));elseprintf("Element not found.");}If we compile and run the above program, it will produce the following result −Input Array: [1 2 3 4 6 7 9 11 12 14 15 16 17 19 33 34 43 45 55 66 ]==================================================Total comparisons made: 19Element found at location: 19](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-116-2048.jpg&f=jpg&w=240)


![Data Structures & Algorithms110PseudocodeThe pseudocode of binary search algorithms should look like this −Procedure binary_searchA ← sorted arrayn ← size of arrayx ← value ot be searchedSet lowerBound = 1Set upperBound = nwhile x not foundif upperBound < lowerBoundEXIT: x does not exists.set midPoint = lowerBound + ( upperBound - lowerBound ) / 2if A[midPoint] < xset lowerBound = midPoint + 1if A[midPoint] > xset upperBound = midPoint - 1if A[midPoint] = xEXIT: x found at location midPointend whileend procedureTo know about binary search implementation using array in C programming language,please click here.](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-119-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms111BinarySearchPrograminCBinary search is a fast search algorithm with run-time complexity of Ο(log n). This searchalgorithm works on the principle of divide and conquer. For this algorithm to work properly,the data collection should be in a sorted form.Implementation in C#include <stdio.h>#define MAX 20// array of items on which linear search will be conducted.int intArray[MAX] = {1,2,3,4,6,7,9,11,12,14,15,16,17,19,33,34,43,45,55,66};void printline(int count){int i;for(i = 0;i <count-1;i++){printf("=");}printf("=n");}int find(int data){int lowerBound = 0;int upperBound = MAX -1;int midPoint = -1;int comparisons = 0;int index = -1;while(lowerBound <= upperBound){printf("Comparison %dn" , (comparisons +1) ) ;printf("lowerBound : %d, intArray[%d] = %dn",lowerBound,lowerBound,intArray[lowerBound]);printf("upperBound : %d, intArray[%d] = %dn",upperBound,upperBound,intArray[upperBound]);](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-120-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms112comparisons++;// compute the mid point// midPoint = (lowerBound + upperBound) / 2;midPoint = lowerBound + (upperBound - lowerBound) / 2;// data foundif(intArray[midPoint] == data){index = midPoint;break;}else {// if data is largerif(intArray[midPoint] < data){// data is in upper halflowerBound = midPoint + 1;}// data is smallerelse{// data is in lower halfupperBound = midPoint -1;}}}printf("Total comparisons made: %d" , comparisons);return index;}void display(){int i;printf("[");// navigate through all itemsfor(i = 0;i<MAX;i++){printf("%d ",intArray[i]);}](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-121-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms113printf("]n");}main(){printf("Input Array: ");display();printline(50);//find location of 1int location = find(55);// if element was foundif(location != -1)printf("nElement found at location: %d" ,(location+1));elseprintf("nElement not found.");}If we compile and run the above program, it will produce the following result −Input Array: [1 2 3 4 6 7 9 11 12 14 15 16 17 19 33 34 43 45 55 66 ]==================================================Comparison 1lowerBound : 0, intArray[0] = 1upperBound : 19, intArray[19] = 66Comparison 2lowerBound : 10, intArray[10] = 15upperBound : 19, intArray[19] = 66Comparison 3lowerBound : 15, intArray[15] = 34upperBound : 19, intArray[19] = 66Comparison 4lowerBound : 18, intArray[18] = 55upperBound : 19, intArray[19] = 66Total comparisons made: 4Element found at location: 19](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-122-2048.jpg&f=jpg&w=240)


![Data Structures & Algorithms116PositionProbinginInterpolationSearchInterpolation search finds a particular item by computing the probe position. Initially, theprobe position is the position of the middle most item of the collection.If a match occurs, then the index of the item is returned. To split the list into two parts,we use the following method −mid = Lo + ((Hi - Lo) / (A[Hi] - A[Lo])) * (X - A[Lo])where −A = listLo = Lowest index of the listHi = Highest index of the listA[n] = Value stored at index n in the listIf the middle item is greater than the item, then the probe position is again calculated inthe sub-array to the right of the middle item. Otherwise, the item is searched in the sub-array to the left of the middle item. This process continues on the sub-array as well untilthe size of subarray reduces to zero.Runtime complexity of interpolation search algorithm is Ο(log (log n)) as comparedto Ο(log n) of BST in favorable situations.AlgorithmAs it is an improvisation of the existing BST algorithm, we are mentioning the steps tosearch the 'target' data value index, using position probing −Step 1 − Start searching data from middle of the list.Step 2 − If it is a match, return the index of the item, and exit.Step 3 − If it is not a match, probe position.Step 4 − Divide the list using probing formula and find the new middle.Step 5 − If data is greater than middle, search in higher sub-list.Step 6 − If data is smaller than middle, search in lower sub-list.Step 7 − Repeat until match.](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-125-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms117PseudocodeA → Array listN → Size of AX → Target ValueProcedure Interpolation_Search()Set Lo → 0Set Mid → -1Set Hi → N-1While X does not matchif Lo equals to Hi OR A[Lo] equals to A[Hi]EXIT: Failure, Target not foundend ifSet Mid = Lo + ((Hi - Lo) / (A[Hi] - A[Lo])) * (X - A[Lo])if A[Mid] = XEXIT: Success, Target found at Midelseif A[Mid] < XSet Lo to Mid+1else if A[Mid] > XSet Hi to Mid-1end ifend ifEnd WhileEnd ProcedureTo know about the implementation of interpolation search in C programminglanguage, click here.](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-126-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms118InterpolationSearchPrograminCInterpolation search is an improved variant of binary search. This search algorithm workson the probing position of the required value. For this algorithm to work properly, the datacollection should be in sorted and equally distributed form.It's runtime complexity is log2(log2 n).Implementation in C#include<stdio.h>#define MAX 10// array of items on which linear search will be conducted.int list[MAX] = { 10, 14, 19, 26, 27, 31, 33, 35, 42, 44 };int find(int data) {int lo = 0;int hi = MAX - 1;int mid = -1;int comparisons = 1;int index = -1;while(lo <= hi) {printf("nComparison %d n" , comparisons ) ;printf("lo : %d, list[%d] = %dn", lo, lo, list[lo]);printf("hi : %d, list[%d] = %dn", hi, hi, list[hi]);comparisons++;// probe the mid pointmid = lo + (((double)(hi - lo) / (list[hi] - list[lo])) * (data - list[lo]));printf("mid = %dn",mid);// data foundif(list[mid] == data) {index = mid;break;}else {](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-127-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms119if(list[mid] < data) {// if data is larger, data is in upper halflo = mid + 1;}else {// if data is smaller, data is in lower halfhi = mid - 1;}}}printf("nTotal comparisons made: %d", --comparisons);return index;}int main() {//find location of 33int location = find(33);// if element was foundif(location != -1)printf("nElement found at location: %d" ,(location+1));elseprintf("Element not found.");return 0;}If we compile and run the above program, it will produce the following result −Comparison 1lo : 0, list[0] = 10hi : 9, list[9] = 44mid = 6Total comparisons made: 1Element found at location: 7You can change the search value and execute the program to test it.](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-128-2048.jpg&f=jpg&w=240)



![Data Structures & Algorithms123struct DataItem *search(int key){//get the hashint hashIndex = hashCode(key);//move in array until an emptywhile(hashArray[hashIndex] != NULL){if(hashArray[hashIndex]->key == key)return hashArray[hashIndex];//go to next cell++hashIndex;//wrap around the tablehashIndex %= SIZE;}return NULL;}InsertOperationWhenever an element is to be inserted, compute the hash code of the key passed andlocate the index using that hash code as an index in the array. Use linear probing forempty location, if an element is found at the computed hash code.void insert(int key,int data){struct DataItem *item = (struct DataItem*) malloc(sizeof(struct DataItem));item->data = data;item->key = key;//get the hashint hashIndex = hashCode(key);//move in array until an empty or deleted cellwhile(hashArray[hashIndex] != NULL && hashArray[hashIndex]->key != -1){//go to next cell++hashIndex;](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-132-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms124//wrap around the tablehashIndex %= SIZE;}hashArray[hashIndex] = item;}DeleteOperationWhenever an element is to be deleted, compute the hash code of the key passed andlocate the index using that hash code as an index in the array. Use linear probing to getthe element ahead if an element is not found at the computed hash code. When found,store a dummy item there to keep the performance of the hash table intact.struct DataItem* delete(struct DataItem* item){int key = item->key;//get the hashint hashIndex = hashCode(key);//move in array until an emptywhile(hashArray[hashIndex] !=NULL){if(hashArray[hashIndex]->key == key){struct DataItem* temp = hashArray[hashIndex];//assign a dummy item at deleted positionhashArray[hashIndex] = dummyItem;return temp;}//go to next cell++hashIndex;//wrap around the tablehashIndex %= SIZE;}return NULL;}](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-133-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms125To know about hash implementation in C programming language, please click here.HashTablePrograminCHash Table is a data structure which stores data in an associative manner. In hash table,the data is stored in an array format where each data value has its own unique indexvalue. Access of data becomes very fast, if we know the index of the desired data.Implementation in C#include <stdio.h>#include <string.h>#include <stdlib.h>#include <stdbool.h>#define SIZE 20struct DataItem {int data;int key;};struct DataItem* hashArray[SIZE];struct DataItem* dummyItem;struct DataItem* item;int hashCode(int key){return key % SIZE;}struct DataItem *search(int key){//get the hashint hashIndex = hashCode(key);//move in array until an emptywhile(hashArray[hashIndex] != NULL){if(hashArray[hashIndex]->key == key)return hashArray[hashIndex];](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-134-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms126//go to next cell++hashIndex;//wrap around the tablehashIndex %= SIZE;}return NULL;}void insert(int key,int data){struct DataItem *item = (struct DataItem*) malloc(sizeof(struct DataItem));item->data = data;item->key = key;//get the hashint hashIndex = hashCode(key);//move in array until an empty or deleted cellwhile(hashArray[hashIndex] != NULL && hashArray[hashIndex]->key != -1){//go to next cell++hashIndex;//wrap around the tablehashIndex %= SIZE;}hashArray[hashIndex] = item;}struct DataItem* delete(struct DataItem* item){int key = item->key;//get the hash](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-135-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms127int hashIndex = hashCode(key);//move in array until an emptywhile(hashArray[hashIndex] != NULL){if(hashArray[hashIndex]->key == key){struct DataItem* temp = hashArray[hashIndex];//assign a dummy item at deleted positionhashArray[hashIndex] = dummyItem;return temp;}//go to next cell++hashIndex;//wrap around the tablehashIndex %= SIZE;}return NULL;}void display(){int i = 0;for(i = 0; i<SIZE; i++) {if(hashArray[i] != NULL)printf(" (%d,%d)",hashArray[i]->key,hashArray[i]->data);elseprintf(" ~~ ");}printf("n");}](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-136-2048.jpg&f=jpg&w=240)









![Data Structures & Algorithms137AlgorithmWe assume list is an array of n elements. We further assume that swap function swapsthe values of the given array elements.begin BubbleSort(list)for all elements of listif list[i] > list[i+1]swap(list[i], list[i+1])end ifend forreturn listend BubbleSortPseudocodeWe observe in algorithm that Bubble Sort compares each pair of array element unless thewhole array is completely sorted in an ascending order. This may cause a few complexityissues like what if the array needs no more swapping as all the elements are alreadyascending.To ease-out the issue, we use one flag variable swapped which will help us see if anyswap has happened or not. If no swap has occurred, i.e. the array requires no moreprocessing to be sorted, it will come out of the loop.Pseudocode of BubbleSort algorithm can be written as follows −procedure bubbleSort( list : array of items )loop = list.count;for i = 0 to loop-1 do:swapped = falsefor j = 0 to loop-1 do:/* compare the adjacent elements */if list[j] > list[j+1] then/* swap them */swap( list[j], list[j+1] )](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-146-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms138swapped = trueend ifend for/*if no number was swapped that meansarray is sorted now, break the loop.*/if(not swapped) thenbreakend ifend forend procedure return listImplementationOne more issue we did not address in our original algorithm and its improvisedpseudocode, is that, after every iteration the highest values settles down at the end of thearray. Hence, the next iteration need not include already sorted elements. For thispurpose, in our implementation, we restrict the inner loop to avoid already sorted values.To know about bubble sort implementation in C programming language, please click here.BubbleSortPrograminCWe shall see the implementation of bubble sort in C programming language here.Implementation in C#include <stdio.h>#include <stdbool.h>#define MAX 10int list[MAX] = {1,8,4,6,0,3,5,2,7,9};void display(){int i;printf("[");](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-147-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms139// navigate through all itemsfor(i = 0; i < MAX; i++){printf("%d ",list[i]);}printf("]n");}void bubbleSort() {int temp;int i,j;bool swapped = false;// loop through all numbersfor(i = 0; i < MAX-1; i++) {swapped = false;// loop through numbers falling aheadfor(j = 0; j < MAX-1-i; j++) {printf(" Items compared: [ %d, %d ] ", list[j],list[j+1]);// check if next number is lesser than current no// swap the numbers.// (Bubble up the highest number)if(list[j] > list[j+1]) {temp = list[j];list[j] = list[j+1];list[j+1] = temp;swapped = true;printf(" => swapped [%d, %d]n",list[j],list[j+1]);}else {printf(" => not swappedn");}](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-148-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms140}// if no number was swapped that means// array is sorted now, break the loop.if(!swapped) {break;}printf("Iteration %d#: ",(i+1));display();}}main(){printf("Input Array: ");display();printf("n");bubbleSort();printf("nOutput Array: ");display();}If we compile and run the above program, it will produce the following result −Input Array: [1 8 4 6 0 3 5 2 7 9 ]Items compared: [ 1, 8 ] => not swappedItems compared: [ 8, 4 ] => swapped [4, 8]Items compared: [ 8, 6 ] => swapped [6, 8]Items compared: [ 8, 0 ] => swapped [0, 8]Items compared: [ 8, 3 ] => swapped [3, 8]Items compared: [ 8, 5 ] => swapped [5, 8]Items compared: [ 8, 2 ] => swapped [2, 8]Items compared: [ 8, 7 ] => swapped [7, 8]Items compared: [ 8, 9 ] => not swapped](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-149-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms141Iteration 1#: [1 4 6 0 3 5 2 7 8 9 ]Items compared: [ 1, 4 ] => not swappedItems compared: [ 4, 6 ] => not swappedItems compared: [ 6, 0 ] => swapped [0, 6]Items compared: [ 6, 3 ] => swapped [3, 6]Items compared: [ 6, 5 ] => swapped [5, 6]Items compared: [ 6, 2 ] => swapped [2, 6]Items compared: [ 6, 7 ] => not swappedItems compared: [ 7, 8 ] => not swappedIteration 2#: [1 4 0 3 5 2 6 7 8 9 ]Items compared: [ 1, 4 ] => not swappedItems compared: [ 4, 0 ] => swapped [0, 4]Items compared: [ 4, 3 ] => swapped [3, 4]Items compared: [ 4, 5 ] => not swappedItems compared: [ 5, 2 ] => swapped [2, 5]Items compared: [ 5, 6 ] => not swappedItems compared: [ 6, 7 ] => not swappedIteration 3#: [1 0 3 4 2 5 6 7 8 9 ]Items compared: [ 1, 0 ] => swapped [0, 1]Items compared: [ 1, 3 ] => not swappedItems compared: [ 3, 4 ] => not swappedItems compared: [ 4, 2 ] => swapped [2, 4]Items compared: [ 4, 5 ] => not swappedItems compared: [ 5, 6 ] => not swappedIteration 4#: [0 1 3 2 4 5 6 7 8 9 ]Items compared: [ 0, 1 ] => not swappedItems compared: [ 1, 3 ] => not swappedItems compared: [ 3, 2 ] => swapped [2, 3]Items compared: [ 3, 4 ] => not swappedItems compared: [ 4, 5 ] => not swappedIteration 5#: [0 1 2 3 4 5 6 7 8 9 ]Items compared: [ 0, 1 ] => not swappedItems compared: [ 1, 2 ] => not swappedItems compared: [ 2, 3 ] => not swappedItems compared: [ 3, 4 ] => not swappedOutput Array: [0 1 2 3 4 5 6 7 8 9 ]](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-150-2048.jpg&f=jpg&w=240)


![Data Structures & Algorithms144We swap them again. By the end of third iteration, we have a sorted sub-list of 4 items.This process goes on until all the unsorted values are covered in a sorted sub-list. Now weshall see some programming aspects of insertion sort.AlgorithmNow we have a bigger picture of how this sorting technique works, so we can derive simplesteps by which we can achieve insertion sort.Step 1 − If it is the first element, it is already sorted. return 1;Step 2 − Pick next elementStep 3 − Compare with all elements in the sorted sub-listStep 4 − Shift all the elements in the sorted sub-list that is greater than thevalue to be sortedStep 5 − Insert the valueStep 6 − Repeat until list is sortedPseudocodeprocedure insertionSort( A : array of items )int holePositionint valueToInsertfor i = 1 to length(A) inclusive do:/* select value to be inserted */valueToInsert = A[i]holePosition = i](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-153-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms145/*locate hole position for the element to be inserted */while holePosition > 0 and A[holePosition-1] > valueToInsert do:A[holePosition] = A[holePosition-1]holePosition = holePosition -1end while/* insert the number at hole position */A[holePosition] = valueToInsertend forend procedureTo know about insertion sort implementation in C programming language, please clickhere.InsertionSortPrograminCThis is an in-place comparison-based sorting algorithm. Here, a sub-list is maintainedwhich is always sorted. For example, the lower part of an array is maintained to be sorted.An element which is to be 'insert'ed in this sorted sub-list, has to find its appropriate placeand then it is to be inserted there. Hence the name insertion sort.Implementation in C#include <stdio.h>#include <stdbool.h>#define MAX 7int intArray[MAX] = {4,6,3,2,1,9,7};void printline(int count){int i;for(i = 0;i <count-1;i++){printf("=");}](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-154-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms146printf("=n");}void display(){int i;printf("[");// navigate through all itemsfor(i = 0;i<MAX;i++){printf("%d ",intArray[i]);}printf("]n");}void insertionSort(){int valueToInsert;int holePosition;int i;// loop through all numbersfor(i = 1; i < MAX; i++){// select a value to be inserted.valueToInsert = intArray[i];// select the hole position where number is to be insertedholePosition = i;// check if previous no. is larger than value to be insertedwhile (holePosition > 0 && intArray[holePosition-1] > valueToInsert){intArray[holePosition] = intArray[holePosition-1];holePosition--;printf(" item moved : %dn" , intArray[holePosition]);}](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-155-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms147if(holePosition != i){printf(" item inserted : %d, at position : %dn" ,valueToInsert,holePosition);// insert the number at hole positionintArray[holePosition] = valueToInsert;}printf("Iteration %d#:",i);display();}}main(){printf("Input Array: ");display();printline(50);insertionSort();printf("Output Array: ");display();printline(50);}If we compile and run the above program, it will produce the following result −Input Array: [4 6 3 2 1 9 7 ]==================================================Iteration 1#:[4 6 3 2 1 9 7 ]item moved : 6item moved : 4item inserted : 3, at position : 0Iteration 2#:[3 4 6 2 1 9 7 ]item moved : 6item moved : 4item moved : 3item inserted : 2, at position : 0Iteration 3#:[2 3 4 6 1 9 7 ]item moved : 6](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-156-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms148item moved : 4item moved : 3item moved : 2item inserted : 1, at position : 0Iteration 4#:[1 2 3 4 6 9 7 ]Iteration 5#:[1 2 3 4 6 9 7 ]item moved : 9item inserted : 7, at position : 5Iteration 6#:[1 2 3 4 6 7 9 ]Output Array: [1 2 3 4 6 7 9 ]==================================================](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-157-2048.jpg&f=jpg&w=240)


![Data Structures & Algorithms151Now, let us learn some programming aspects of selection sort.AlgorithmStep 1 − Set MIN to location 0Step 2 − Search the minimum element in the listStep 3 − Swap with value at location MINStep 4 − Increment MIN to point to next elementStep 5 − Repeat until list is sortedPseudocodeprocedure selection sortlist : array of itemsn : size of listfor i = 1 to n - 1/* set current element as minimum*/min = i/* check the element to be minimum */for j = i+1 to nif list[j] < list[min] thenmin = j;end ifend for/* swap the minimum element with the current element*/if indexMin != i thenswap list[min] and list[i]end ifend forend procedureTo know about selection sort implementation in C programming language, please clickhere.](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-160-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms152SelectionSortPrograminCSelection sort is a simple sorting algorithm. This sorting algorithm is an in-placecomparison-based algorithm in which the list is divided into two parts, the sorted part atthe left end and the unsorted part at the right end. Initially, the sorted part is empty andthe unsorted part is the entire list.Implementation in C#include <stdio.h>#include <stdbool.h>#define MAX 7int intArray[MAX] = {4,6,3,2,1,9,7};void printline(int count){int i;for(i = 0;i <count-1;i++){printf("=");}printf("=n");}void display(){int i;printf("[");// navigate through all itemsfor(i = 0;i<MAX;i++){printf("%d ", intArray[i]);}](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-161-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms153printf("]n");}void selectionSort(){int indexMin,i,j;// loop through all numbersfor(i = 0; i < MAX-1; i++){// set current element as minimumindexMin = i;// check the element to be minimumfor(j = i+1;j<MAX;j++){if(intArray[j] < intArray[indexMin]){indexMin = j;}}if(indexMin != i){printf("Items swapped: [ %d, %d ]n" , intArray[i],intArray[indexMin]);// swap the numbersint temp = intArray[indexMin];intArray[indexMin] = intArray[i];intArray[i] = temp;}printf("Iteration %d#:",(i+1));display();}}](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-162-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms154main(){printf("Input Array: ");display();printline(50);selectionSort();printf("Output Array: ");display();printline(50);}If we compile and run the above program, it will produce the following result −Input Array: [4 6 3 2 1 9 7 ]==================================================Items swapped: [ 4, 1 ]Iteration 1#:[1 6 3 2 4 9 7 ]Items swapped: [ 6, 2 ]Iteration 2#:[1 2 3 6 4 9 7 ]Iteration 3#:[1 2 3 6 4 9 7 ]Items swapped: [ 6, 4 ]Iteration 4#:[1 2 3 4 6 9 7 ]Iteration 5#:[1 2 3 4 6 9 7 ]Items swapped: [ 9, 7 ]Iteration 6#:[1 2 3 4 6 7 9 ]Output Array: [1 2 3 4 6 7 9 ]==================================================](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-163-2048.jpg&f=jpg&w=240)

![Data Structures & Algorithms156In the next iteration of the combining phase, we compare lists of two data values, andmerge them into a list of found data values placing all in a sorted order.After the final merging, the list should look like this −Now we should learn some programming aspects of merge sorting.AlgorithmMerge sort keeps on dividing the list into equal halves until it can no more be divided. Bydefinition, if it is only one element in the list, it is sorted. Then, merge sort combines thesmaller sorted lists keeping the new list sorted too.Step 1 − if it is only one element in the list it is already sorted, return.Step 2 − divide the list recursively into two halves until it can no more bedivided.Step 3 − merge the smaller lists into new list in sorted order.PseudocodeWe shall now see the pseudocodes for merge sort functions. As our algorithms point outtwo main functions − divide & merge.Merge sort works with recursion and we shall see our implementation in the same way.procedure mergesort( var a as array )if ( n == 1 ) return avar l1 as array = a[0] ... a[n/2]var l2 as array = a[n/2+1] ... a[n]l1 = mergesort( l1 )](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-165-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms157l2 = mergesort( l2 )return merge( l1, l2 )end procedureprocedure merge( var a as array, var b as array )var c as arraywhile ( a and b have elements )if ( a[0] > b[0] )add b[0] to the end of cremove b[0] from belseadd a[0] to the end of cremove a[0] from aend ifend whilewhile ( a has elements )add a[0] to the end of cremove a[0] from aend whilewhile ( b has elements )add b[0] to the end of cremove b[0] from bend whilereturn cend procedureTo know about merge sort implementation in C programming language, please click here.](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-166-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms158MergeSortPrograminCMerge sort is a sorting technique based on divide and conquer technique. With the worst-case time complexity being Ο(n log n), it is one of the most respected algorithms.Implementation in CWe shall see the implementation of merge sort in C programming language here −#include <stdio.h>#define max 10int a[10] = { 10, 14, 19, 26, 27, 31, 33, 35, 42, 44 };int b[10];void merging(int low, int mid, int high) {int l1, l2, i;for(l1 = low, l2 = mid + 1, i = low; l1 <= mid && l2 <= high; i++) {if(a[l1] <= a[l2])b[i] = a[l1++];elseb[i] = a[l2++];}while(l1 <= mid)b[i++] = a[l1++];while(l2 <= high)b[i++] = a[l2++];for(i = low; i <= high; i++)a[i] = b[i];}void sort(int low, int high) {int mid;if(low < high) {](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-167-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms159mid = (low + high) / 2;sort(low, mid);sort(mid+1, high);merging(low, mid, high);}else {return;}}int main() {int i;printf("List before sortingn");for(i = 0; i <= max; i++)printf("%d ", a[i]);sort(0, max);printf("nList after sortingn");for(i = 0; i <= max; i++)printf("%d ", a[i]);}If we compile and run the above program, it will produce the following result −List before sorting10 14 19 26 27 31 33 35 42 44 0List after sorting0 10 14 19 26 27 31 33 35 42 44](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-168-2048.jpg&f=jpg&w=240)



![Data Structures & Algorithms163We see that it required only four swaps to sort the rest of the array.AlgorithmFollowing is the algorithm for shell sort.Step 1 − Initialize the value of hStep 2 − Divide the list into smaller sub-list of equal interval hStep 3 − Sort these sub-lists using insertion sortStep 3 − Repeat until complete list is sortedPseudocodeFollowing is the pseudocode for shell sort.procedure shellSort()A : array of items/* calculate interval*/while interval < A.length /3 do:interval = interval * 3 + 1end whilewhile interval > 0 do:for outer = interval; outer < A.length; outer ++ do:/* select value to be inserted */valueToInsert = A[outer]inner = outer;/*shift element towards right*/while inner > interval -1 && A[inner - interval] >= valueToInsert do:A[inner] = A[inner - interval]inner = inner - intervalend while](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-172-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms164/* insert the number at hole position */A[inner] = valueToInsertend for/* calculate interval*/interval = (interval -1) /3;end whileend procedureTo know about shell sort implementation in C programming language, please click here.ShellSortPrograminCShell sort is a highly efficient sorting algorithm and is based on insertion sort algorithm.This algorithm avoids large shifts as in case of insertion sort, if the smaller value is to thefar right and has to be moved to the far left.Implementation in C#include <stdio.h>#include <stdbool.h>#define MAX 7int intArray[MAX] = {4,6,3,2,1,9,7};void printline(int count){int i;for(i = 0;i <count-1;i++){printf("=");}printf("=n");}](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-173-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms165void display(){int i;printf("[");// navigate through all itemsfor(i = 0;i<MAX;i++){printf("%d ",intArray[i]);}printf("]n");}void shellSort(){int inner, outer;int valueToInsert;int interval = 1;int elements = MAX;int i = 0;while(interval <= elements/3) {interval = interval*3 +1;}while(interval > 0) {printf("iteration %d#:",i);display();for(outer = interval; outer < elements; outer++) {valueToInsert = intArray[outer];inner = outer;while(inner > interval -1 && intArray[inner - interval]>= valueToInsert) {intArray[inner] = intArray[inner - interval];inner -=interval;printf(" item moved :%dn",intArray[inner]);}](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-174-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms166intArray[inner] = valueToInsert;printf(" item inserted :%d, at position :%dn",valueToInsert,inner);}interval = (interval -1) /3;i++;}}int main() {printf("Input Array: ");display();printline(50);shellSort();printf("Output Array: ");display();printline(50);return 1;}If we compile and run the above program, it will produce the following result −Input Array: [4 6 3 2 1 9 7 ]==================================================iteration 0#:[4 6 3 2 1 9 7 ]item moved :4item inserted :1, at position :0item inserted :9, at position :5item inserted :7, at position :6iteration 1#:[1 6 3 2 4 9 7 ]item inserted :6, at position :1item moved :6item inserted :3, at position :1item moved :6](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-175-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms167item moved :3item inserted :2, at position :1item moved :6item inserted :4, at position :3item inserted :9, at position :5item moved :9item inserted :7, at position :5Output Array: [1 2 3 4 6 7 9 ]==================================================](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-176-2048.jpg&f=jpg&w=240)

![Data Structures & Algorithms169QuickSortPivotPseudocodeThe pseudocode for the above algorithm can be derived as −function partitionFunc(left, right, pivot)leftPointer = left -1rightPointer = rightwhile True dowhile A[++leftPointer] < pivot do//do-nothingend whilewhile rightPointer > 0 && A[--rightPointer] > pivot do//do-nothingend whileif leftPointer >= rightPointerbreakelseswap leftPointer,rightPointerend ifend whileswap leftPointer,rightreturn leftPointerend functionQuickSortAlgorithmUsing pivot algorithm recursively, we end up with smaller possible partitions. Eachpartition is then processed for quick sort. We define recursive algorithm for quicksort asfollows −Step 1 − Make the right-most index value pivotStep 2 − partition the array using pivot valueStep 3 − quicksort left partition recursivelyStep 4 − quicksort right partition recursively](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-178-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms170QuickSortPseudocodeTo get more into it, let see the pseudocode for quick sort algorithm −procedure quickSort(left, right)if right-left <= 0returnelsepivot = A[right]partition = partitionFunc(left, right, pivot)quickSort(left,partition-1)quickSort(partition+1,right)end ifend procedureTo know about quick sort implementation in C programming language, please click here.QuickSortPrograminCQuick sort is a highly efficient sorting algorithm and is based on partitioning of array ofdata into smaller arrays. A large array is partitioned into two arrays one of which holdsvalues smaller than the specified value, say pivot, based on which the partition is madeand another array holds values greater than the pivot value.Implementation in C#include <stdio.h>#include <stdbool.h>#define MAX 7int intArray[MAX] = {4,6,3,2,1,9,7};void printline(int count){int i;for(i = 0;i <count-1;i++){printf("=");}](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-179-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms171printf("=n");}void display(){int i;printf("[");// navigate through all itemsfor(i = 0;i<MAX;i++){printf("%d ",intArray[i]);}printf("]n");}void swap(int num1, int num2){int temp = intArray[num1];intArray[num1] = intArray[num2];intArray[num2] = temp;}int partition(int left, int right, int pivot){int leftPointer = left -1;int rightPointer = right;while(true){while(intArray[++leftPointer] < pivot){//do nothing}while(rightPointer > 0 && intArray[--rightPointer] > pivot){//do nothing}if(leftPointer >= rightPointer){break;}else{](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-180-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms172printf(" item swapped :%d,%dn",intArray[leftPointer],intArray[rightPointer]);swap(leftPointer,rightPointer);}}printf(" pivot swapped :%d,%dn", intArray[leftPointer],intArray[right]);swap(leftPointer,right);printf("Updated Array: ");display();return leftPointer;}void quickSort(int left, int right){if(right-left <= 0){return;}else {int pivot = intArray[right];int partitionPoint = partition(left, right, pivot);quickSort(left,partitionPoint-1);quickSort(partitionPoint+1,right);}}main(){printf("Input Array: ");display();printline(50);quickSort(0,MAX-1);printf("Output Array: ");display();printline(50);}](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-181-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms173If we compile and run the above program, it will produce the following result −Input Array: [4 6 3 2 1 9 7 ]==================================================pivot swapped :9,7Updated Array: [4 6 3 2 1 7 9 ]pivot swapped :4,1Updated Array: [1 6 3 2 4 7 9 ]item swapped :6,2pivot swapped :6,4Updated Array: [1 2 3 4 6 7 9 ]pivot swapped :3,3Updated Array: [1 2 3 4 6 7 9 ]Output Array: [1 2 3 4 6 7 9 ]==================================================](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-182-2048.jpg&f=jpg&w=240)








![Data Structures & Algorithms182//stack variablesint stack[MAX];int top = -1;//graph variables//array of verticesstruct Vertex* lstVertices[MAX];//adjacency matrixint adjMatrix[MAX][MAX];//vertex countint vertexCount = 0;//stack functionsvoid push(int item) {stack[++top] = item;}int pop() {return stack[top--];}int peek() {return stack[top];}bool isStackEmpty() {return top == -1;}](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-191-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms183//graph functions//add vertex to the vertex listvoid addVertex(char label) {struct Vertex* vertex = (struct Vertex*) malloc(sizeof(struct Vertex));vertex->label = label;vertex->visited = false;lstVertices[vertexCount++] = vertex;}//add edge to edge arrayvoid addEdge(int start,int end) {adjMatrix[start][end] = 1;adjMatrix[end][start] = 1;}//display the vertexvoid displayVertex(int vertexIndex) {printf("%c ",lstVertices[vertexIndex]->label);}//get the adjacent unvisited vertexint getAdjUnvisitedVertex(int vertexIndex) {int i;for(i = 0; i<vertexCount; i++) {if(adjMatrix[vertexIndex][i] == 1 && lstVertices[i]->visited == false) {return i;}}return -1;}](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-192-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms184void depthFirstSearch() {int i;//mark first node as visitedlstVertices[0]->visited = true;//display the vertexdisplayVertex(0);//push vertex index in stackpush(0);while(!isStackEmpty()) {//get the unvisited vertex of vertex which is at top of the stackint unvisitedVertex = getAdjUnvisitedVertex(peek());//no adjacent vertex foundif(unvisitedVertex == -1) {pop();}else {lstVertices[unvisitedVertex]->visited = true;displayVertex(unvisitedVertex);push(unvisitedVertex);}}//stack is empty, search is complete, reset the visited flagfor(i = 0;i < vertexCount;i++) {lstVertices[i]->visited = false;}}](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-193-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms185int main() {int i, j;for(i = 0; i<MAX; i++) // set adjacency {for(j = 0; j<MAX; j++) // matrix to 0adjMatrix[i][j] = 0;}addVertex('S'); // 0addVertex('A'); // 1addVertex('B'); // 2addVertex('C'); // 3addVertex('D'); // 4addEdge(0, 1); // S - AaddEdge(0, 2); // S - BaddEdge(0, 3); // S - CaddEdge(1, 4); // A - DaddEdge(2, 4); // B - DaddEdge(3, 4); // C - Dprintf("Depth First Search: ");depthFirstSearch();return 0;}If we compile and run the above program, it will produce the following result −Depth First Search: S A D B C](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-194-2048.jpg&f=jpg&w=240)



![Data Structures & Algorithms189Implementation in C#include <stdio.h>#include <stdlib.h>#include <stdbool.h>#define MAX 5struct Vertex {char label;bool visited;};//queue variablesint queue[MAX];int rear = -1;int front = 0;int queueItemCount = 0;//graph variables](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-198-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms190//array of verticesstruct Vertex* lstVertices[MAX];//adjacency matrixint adjMatrix[MAX][MAX];//vertex countint vertexCount = 0;//queue functionsvoid insert(int data) {queue[++rear] = data;queueItemCount++;}int removeData() {queueItemCount--;return queue[front++];}bool isQueueEmpty() {return queueItemCount == 0;}//graph functions//add vertex to the vertex listvoid addVertex(char label) {struct Vertex* vertex = (struct Vertex*) malloc(sizeof(struct Vertex));vertex->label = label;vertex->visited = false;lstVertices[vertexCount++] = vertex;}](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-199-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms191//add edge to edge arrayvoid addEdge(int start,int end) {adjMatrix[start][end] = 1;adjMatrix[end][start] = 1;}//display the vertexvoid displayVertex(int vertexIndex) {printf("%c ",lstVertices[vertexIndex]->label);}//get the adjacent unvisited vertexint getAdjUnvisitedVertex(int vertexIndex) {int i;for(i = 0; i<vertexCount; i++) {if(adjMatrix[vertexIndex][i] == 1 && lstVertices[i]->visited == false)return i;}return -1;}void breadthFirstSearch() {int i;//mark first node as visitedlstVertices[0]->visited = true;//display the vertexdisplayVertex(0);](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-200-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms192//insert vertex index in queueinsert(0);int unvisitedVertex;while(!isQueueEmpty()) {//get the unvisited vertex of vertex which is at front of the queueint tempVertex = removeData();//no adjacent vertex foundwhile((unvisitedVertex = getAdjUnvisitedVertex(tempVertex)) != -1) {lstVertices[unvisitedVertex]->visited = true;displayVertex(unvisitedVertex);insert(unvisitedVertex);}}//queue is empty, search is complete, reset the visited flagfor(i = 0;i<vertexCount;i++) {lstVertices[i]->visited = false;}}int main() {int i, j;for(i = 0; i<MAX; i++) // set adjacency {for(j = 0; j<MAX; j++) // matrix to 0adjMatrix[i][j] = 0;}addVertex('S'); // 0addVertex('A'); // 1addVertex('B'); // 2addVertex('C'); // 3addVertex('D'); // 4](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-201-2048.jpg&f=jpg&w=240)











![Data Structures & Algorithms204}}void post_order_traversal(struct node* root) {if(root != NULL) {post_order_traversal(root->leftChild);post_order_traversal(root->rightChild);printf("%d ", root->data);}}int main() {int i;int array[7] = { 27, 14, 35, 10, 19, 31, 42 };for(i = 0; i < 7; i++)insert(array[i]);i = 31;struct node * temp = search(i);if(temp != NULL) {printf("[%d] Element found.", temp->data);printf("n");}else {printf("[ x ] Element not found (%d).n", i);}i = 15;temp = search(i);if(temp != NULL) {printf("[%d] Element found.", temp->data);printf("n");}else {printf("[ x ] Element not found (%d).n", i);}](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-213-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms205printf("nPreorder traversal: ");pre_order_traversal(root);printf("nInorder traversal: ");inorder_traversal(root);printf("nPost order traversal: ");post_order_traversal(root);return 0;}If we compile and run the above program, it will produce the following result −Visiting elements: 27 35 [31] Element found.Visiting elements: 27 14 19 [ x ] Element not found (15).Preorder traversal: 27 14 10 19 35 31 42Inorder traversal: 10 14 19 27 31 35 42Post order traversal: 10 19 14 31 42 35 27](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-214-2048.jpg&f=jpg&w=240)







![Data Structures & Algorithms213int i;int array[7] = { 27, 14, 35, 10, 19, 31, 42 };for(i = 0; i < 7; i++)insert(array[i]);i = 31;struct node * temp = search(i);if(temp != NULL) {printf("[%d] Element found.", temp->data);printf("n");}else {printf("[ x ] Element not found (%d).n", i);}i = 15;temp = search(i);if(temp != NULL) {printf("[%d] Element found.", temp->data);printf("n");}else {printf("[ x ] Element not found (%d).n", i);}printf("nPreorder traversal: ");pre_order_traversal(root);printf("nInorder traversal: ");inorder_traversal(root);printf("nPost order traversal: ");post_order_traversal(root);return 0;}](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-222-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms214If we compile and run the above program, it will produce the following result −Visiting elements: 27 35 [31] Element found.Visiting elements: 27 14 19 [ x ] Element not found (15).Preorder traversal: 27 14 10 19 35 31 42Inorder traversal: 10 14 19 27 31 35 42Post order traversal: 10 19 14 31 42 35 27](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-223-2048.jpg&f=jpg&w=240)
































![Data Structures & Algorithms247TowerofHanoiinCProgram#include <stdio.h>#include <stdbool.h>#define MAX 10int list[MAX] = {1,8,4,6,0,3,5,2,7,9};void display(){int i;printf("[");// navigate through all itemsfor(i = 0; i < MAX; i++){printf("%d ",list[i]);}printf("]n");}void bubbleSort() {int temp;int i,j;bool swapped = false;// loop through all numbersfor(i = 0; i < MAX-1; i++) {swapped = false;// loop through numbers falling aheadfor(j = 0; j < MAX-1-i; j++) {printf("Items compared: [ %d, %d ] ", list[j],list[j+1]);](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-256-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms248// check if next number is lesser than current no// swap the numbers.// (Bubble up the highest number)if(list[j] > list[j+1]) {temp = list[j];list[j] = list[j+1];list[j+1] = temp;swapped = true;printf(" => swapped [%d, %d]n",list[j],list[j+1]);}else {printf(" => not swappedn");}}// if no number was swapped that means// array is sorted now, break the loop.if(!swapped) {break;}printf("Iteration %d#: ",(i+1));display();}}main(){printf("Input Array: ");display();printf("n");bubbleSort();printf("nOutput Array: ");display();}](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-257-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms249If we compile and run the above program, it will produce the following result −Input Array: [1 8 4 6 0 3 5 2 7 9 ]Items compared: [ 1, 8 ] => not swappedItems compared: [ 8, 4 ] => swapped [4, 8]Items compared: [ 8, 6 ] => swapped [6, 8]Items compared: [ 8, 0 ] => swapped [0, 8]Items compared: [ 8, 3 ] => swapped [3, 8]Items compared: [ 8, 5 ] => swapped [5, 8]Items compared: [ 8, 2 ] => swapped [2, 8]Items compared: [ 8, 7 ] => swapped [7, 8]Items compared: [ 8, 9 ] => not swappedIteration 1#: [1 4 6 0 3 5 2 7 8 9 ]Items compared: [ 1, 4 ] => not swappedItems compared: [ 4, 6 ] => not swappedItems compared: [ 6, 0 ] => swapped [0, 6]Items compared: [ 6, 3 ] => swapped [3, 6]Items compared: [ 6, 5 ] => swapped [5, 6]Items compared: [ 6, 2 ] => swapped [2, 6]Items compared: [ 6, 7 ] => not swappedItems compared: [ 7, 8 ] => not swappedIteration 2#: [1 4 0 3 5 2 6 7 8 9 ]Items compared: [ 1, 4 ] => not swappedItems compared: [ 4, 0 ] => swapped [0, 4]Items compared: [ 4, 3 ] => swapped [3, 4]Items compared: [ 4, 5 ] => not swappedItems compared: [ 5, 2 ] => swapped [2, 5]Items compared: [ 5, 6 ] => not swappedItems compared: [ 6, 7 ] => not swappedIteration 3#: [1 0 3 4 2 5 6 7 8 9 ]Items compared: [ 1, 0 ] => swapped [0, 1]Items compared: [ 1, 3 ] => not swappedItems compared: [ 3, 4 ] => not swappedItems compared: [ 4, 2 ] => swapped [2, 4]Items compared: [ 4, 5 ] => not swappedItems compared: [ 5, 6 ] => not swapped](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-258-2048.jpg&f=jpg&w=240)
![Data Structures & Algorithms250Iteration 4#: [0 1 3 2 4 5 6 7 8 9 ]Items compared: [ 0, 1 ] => not swappedItems compared: [ 1, 3 ] => not swappedItems compared: [ 3, 2 ] => swapped [2, 3]Items compared: [ 3, 4 ] => not swappedItems compared: [ 4, 5 ] => not swappedIteration 5#: [0 1 2 3 4 5 6 7 8 9 ]Items compared: [ 0, 1 ] => not swappedItems compared: [ 1, 2 ] => not swappedItems compared: [ 2, 3 ] => not swappedItems compared: [ 3, 4 ] => not swappedOutput Array: [0 1 2 3 4 5 6 7 8 9 ]](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2flearndatastructuresalgorithmstutorial-180620080749%2f75%2fLearn-data-structures-algorithms-tutorial-259-2048.jpg&f=jpg&w=240)




