SlideShare a Scribd company logo
Data Structures
Which of the following is faster? A binary search of an ordered set of elements in an array or a sequential search of the elements?
The binary search is faster than the sequential search.  The complexity of binary search is 'log n' whereas the complexity of a sequential search is 'n'.   In a binary search, each time we proceed, we have to deal with only half of the elements of the array compared to the previous one. So the search is faster.
List out the areas in which data structures are applied extensively?
Which data structure is used to perform recursion?
Stack. Because of its LIFO (Last In First Out) property it remembers its caller and hence knows where to return to when the function has to return.  Recursion makes use of system stack for storing the return addresses of the function calls.  Every recursive function has its equivalent iterative (non-recursive) function.  Even when such equivalent iterative procedures are written, explicit stack is to be used.
Tree can have duplicate values :      True (or) False?
True Tree defines the structure of an acyclic graph but does not disallow duplicates.
The size of a Tree is the number of nodes in the Tree : True (or) False?
True The size denotes the number of nodes, height denotes the longest path from leaf node to root node.
Ram is told to sort a set of Data using Data structure. He has been told to use one of the following Methods  Insertion Selection Exchange Linear Now Ram says a Method from the above can not be used to sort.  Which is the method?
Linear Using insertion we can perform insertion sort, using selection we can perform selection sort, and using exchange we can perform bubble sort.  But no sorting method is possible using linear method;  Linear is a searching method
Ashok is told to manipulate an Arithmetic Expression. What is the data structure he will use?  Linked List Tree Graph Stack
Stack Stacks are used to evaluate the algebraic or arithmetic expressions using prefix or postfix notations
There are 8,15,13,14 nodes in 4 different trees. Which of them could form a full binary tree?  8 15 13 14
In general,  there are 2n – 1 nodes in a full binary tree.  By the method of elimination: Full binary tree contains odd number of nodes.  So there cannot be a full binary tree with 8 or 14 nodes. With 13 nodes,  you can form a complete binary tree but not a full binary tree. Full and complete binary trees are different All full binary trees are complete binary trees but not vice versa
A B C D E F G Full binary Tree: A binary tree is a full binary tree if and only if: Each non leaf node has exactly two child nodes All leaf nodes have identical path length It is called full since all possible node slots are occupied
A B C G D E F H I J K Complete binary Tree: A complete binary tree (of height h) satisfies the following conditions: Level 0 to h-1 represent a full binary tree of height h-1 One or more nodes in level h-1 may have 0, or 1 child nodes
How many null branches are there in a binary tree with 20 nodes?
21 (null branches) Let’s consider a tree with 5 nodes So the total number of null nodes in a binary tree of n nodes is n+1 Null branches
Write an algorithm to detect loop in a linked list. 	You are presented with a linked list, which may have a "loop" in it. That is, an element of the linked list may incorrectly point to a previously encountered element, which can cause an infinite loop when traversing the list. Devise an algorithm to detect whether a loop exists in a linked list. How does your answer change if you cannot change the structure of the list elements?
One possible answer is to add a flag to each element of the list.  You could then traverse the list, starting at the head and tagging each element as you encounter it.  If you ever encountered an element that was already tagged, you would know that you had already visited it     and that there existed a loop in the linked list.  What if you are not allowed to alter the structure of the elements of the linked list?
The following algorithm will find the loop: Start with two pointers ptr1 and ptr2. Set ptr1 and ptr2 to the head of the linked list. Traverse the linked list with ptr1 moving twice as fast as ptr2 (for every two elements that ptr1 advances within the list, advance ptr2 by one element). Stop when ptr1 reaches the end of the list, or when ptr1 = ptr2. If ptr1 and ptr2 are ever equal, then there must be a loop in the linked list. If the linked list has no loops, ptr1 should reach the end of the linked list ahead of ptr2
The Operation that is not allowed in a binary search tree is Location Change Search Deletion Insertion
Location Change
Array is a type of ________________  data structure. Non Homogenous Non Linear Homogenous but not Linear Both Homogenous and Linear
Both Homogenous and Linear.
The address of a node in a data structure is called Pointer Referencer Link All the above
All the above
The minimum number of edges in a connected cycle graph on n vertices is ________ n n + 1 n – 1 2n
n
The total number of passes required in a selection sort is n + 1 n – 1 n n * n
n – 1
The node that  does not have any sub trees is called ___________ Null Node Zero Node Leaf Node Empty Node
Leaf Node
Linked List is a Static Data Structure Primitive Data Structure Dynamic Data Structure None of the above
Dynamic Data Structure
Which data structure is needed to convert infix notation to postfix notation. Tree Linear Linked List Stack Queue
Stack
If every node u in Graph (G) is adjacent to every other node v in G, it is called as _____ graph. Directed Graph Complete Graph Connected Graph Multi Graph
Complete Graph
Bubble sort is an example of Selection sort technique Exchange sort technique Quick sort technique None of the options
Exchange sort technique
How do you chose the best algorithm among available algorithms to solve a problem Based on space complexity Based on programming requirements Based on time complexity All the above
All the above
Which of the following are called descendants? All the leaf nodes Parents, grandparents Root node Children, grandchildren
Children, grandchildren
Choose the limitation of an array from the below options. Memory Management is very poor Searching is slower Insertion and deletion are costlier  Insertion and Deletion is not possible
Insertion and deletion are costlier  (It involves shifting rest of the elements)
Areas where stacks are popularly used are. Subroutines Expression Handling Recursion All the above
All the above
How would you implement queue using stack(s)?
Use a temp stack Data In into queue Push the element into the original stack Data Out from queue Pop all the elements from stack into a temp stackpop out the first element from the temp stack
Write a C program to compare two linked lists.
int compare_linked_lists(struct node *q, struct node *r){  static int flag;  if((q==NULL ) && (r==NULL)){   flag=1;  }  else{   if(q==NULL || r==NULL){    flag=0;   }  if(q->data!=r->data){   flag=0;  }  else{ compare_linked_lists(q->link,r->link);   }  }  return(flag); }
Write a C program to return the nth node from the end of a linked list.
Suppose one needs to get to the 6th node from the end in the LL. First, just keep on incrementing the first pointer (ptr1) till the number of increments cross n (which is 6 in this case)  STEP 1 : 1(ptr1,ptr2) -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> 10 STEP 2 : 1(ptr2) -> 2 -> 3 -> 4 -> 5 -> 6(ptr1) -> 7 -> 8 -> 9 -> 10  Now, start the second pointer (ptr2) and keep on incrementing it till the first pointer (ptr1) reaches the end of the LL.  STEP 3 : 1 -> 2 -> 3 -> 4(ptr2) -> 5 -> 6 -> 7 -> 8 -> 9 -> 10 (ptr1)   So here you have the 6th node from the end pointed to by ptr2!
struct node { int data; struct node *next; }mynode; mynode * nthNode(mynode *head, int n /*pass 0 for last node*/) { mynode *ptr1,*ptr2; int count; if(!head) { return(NULL); } ptr1  = head; ptr2  = head; count = 0;
while(count < n) { count++; if((ptr1=ptr1->next)==NULL) { //Length of the linked list less than n. Error. return(NULL); } } while((ptr1=ptr1->next)!=NULL) { ptr2=ptr2->next; } return(ptr2); }
Write a C program to insert nodes into a linked list in a sorted fashion?
The solution is to iterate down the list looking for the correct place to insert the new node. That could be the end of the list, or a point just before a node which is larger than the new node.  Let us assume the memory for the new node has already been allocated and a pointer to that memory is being passed to this function. // Special case code for the head end void linkedListInsertSorted(struct node** headReference, struct node* newNode) { // Special case for the head end if (*headReference == NULL || (*headReference)->data >= newNode->data){ newNode->next = *headReference;
*headReference = newNode; } else { // Locate the node before which the insertion is to happen! struct node* current = *headReference; while (current->next!=NULL && current->next->data < newNode->data){ current = current->next; } newNode->next = current->next; current->next = newNode; } }
Write a C program to remove duplicates from a sorted linked list?
As the linked list is sorted, we can start from the beginning of the list and compare adjacent nodes.  When adjacent nodes are the same, remove the second one. There's a tricky case where the node after the next node needs to be noted before the deletion. // Remove duplicates from a sorted list void RemoveDuplicates(struct node* head) { struct node* current = head;  if (current == NULL) return; // do nothing if the list is empty  // Compare current node with next node  while(current->next!=NULL)  {
  if (current->data == current->next->data)   { struct node* nextNext = current->next->next;     free(current->next);     current->next = nextNext;   }   else   {      current = current->next; // only advance if no   deletion   }  } }
Write a C program to find the depth or height of a tree.
#define max(x,y) ((x)>(y)?(x):(y)) structBintree {  int element; structBintree *left; structBintree *right; }; typedefstructBintree* Tree; int height(Tree T) {  if(!T)    return -1;  else   return (1 + max(height(T->left), height(T->right))) }
Write C code to determine if two trees are identical
structBintree {  int element; structBintree *left; structBintree *right; }; typedefstructBintree* Tree; int CheckIdentical( Tree T1, Tree T2 ) {  if(!T1 && !T2) // If both tree are NULL then return true   return 1;
else if((!T1 && T2) || (T1 && !T2)) //If either of one is NULL, return false  return 0; else  return ((T1->element == T2->element) && CheckIdentical(T1->left, T2-i>left) && CheckIdentical(T1->right, T2->right));   // if element of both tree are same and left and right tree is also same then both trees are same  }
Write a  C code to create a copy of a Tree
mynode *copy(mynode *root) { mynode *temp;  if(root==NULL)return(NULL);  temp = (mynode *) malloc(sizeof(mynode));  temp->value = root->value;  temp->left  = copy(root->left);  temp->right = copy(root->right);  return(temp); }
Which of the following are called siblings Children of the same parent All nodes in the given path upto leaf node All nodes in a sub tree Children, Grand Children
Children of the same parent
Linked List can grow and shrink in size dynamically at __________ . Runtime Compile time
Runtime
The postfix of A+(B*C) is  ABC*+ AB+C* ABC+* +A*BC
ABC*+
Data structure using sequential allocation is called  Linear Data Structure Non-Linear Data Structure Non-primitive Data Structure Sequence Data Structure
Linear Data Structure
A linear list in which elements can be added or removed at either end but not in the middle is known as Tree Queue Dequeue Stack
Dequeue
The average number of key comparisons done in a successful sequential search in list of length n is  n+1/2 n-1/2 n/2 log n
n+1/2
A full binary tree with n leaves contains __________ nlog2n nodes 2^n nodes (2n-1) nodes n nodes
(2n-1) nodes
If a node has positive outdegree and zero indegree, it is called a __________. Source Sink outdegreenode indegreenode
Source
The postfix notation for ((A+B)^C-(D-E)^(F+G)) is  AB + C*DE—FG+^ ^-*+ABC –DE + FG ^+AB*C—DE^+FG ABC + CDE *-- FG +^
AB + C*DE—FG+^
If you are using C language to implement the heterogeneous linked list, what pointer type will you use?
The heterogeneous linked list contains different data types in its nodes and we need a pointer to connect them.  It is not possible to use ordinary pointers for this.  So we use void pointer.  Void pointer is capable of storing pointer to anytype of data (eg., integer or character) as it is a generic pointer type.
What is heap sort?
A Heap is an almost complete binary tree.  In this tree, if the maximum level is i, then, upto the (i-1)th level should be complete. At level i, the number of nodes can be less than or equal to 2^i. If the number of nodes is less than 2^i, then the nodes in that level should be completely filled, only from left to right The property of an ascending heap is that, the root is the lowest and given any other node i, that node should be less than its left child and its right child. In a descending heap, the root should be the highest and given any other node i, that node should be greater than its left child and right child.
To sort the elements, one should create the heap first. Once the heap is created, the root has the highest value. Now we need to sort the elements in ascending order. The root can not be exchanged with the nth element so that the item in the nth position is sorted. Now, sort the remaining (n-1) elements. This can be achieved by reconstructing the heap for (n-1) elements.
heapsort()  {  n = array();   // Convert the tree into an array. makeheap(n);   // Construct the initial heap.  for(i=n; i>=2; i--)    {     swap(s[1],s[i]); heapsize--; keepheap(i);    } } makeheap(n) { heapsize=n;  for(i=n/2; i>=1; i--) keepheap(i); } keepheap(i) {   l = 2*i;   r = 2*i + 1;   p = s[l];   q = s[r];   t = s[i];
if(l<=heapsize && p->value > t->value) largest = l;    else      largest = i;    m = s[largest];    if(r<=heapsize && q->value > m->value)      largest = r;    if(largest != i)    {       swap(s[i], s[largest]); keepheap(largest);    } }
Implement the bubble sort algorithm. How can it be improved? Write the code for selection sort, quick sort, insertion sort.
Bubble sort algorithm void bubble_sort(int a[], int n) {   int i, j, temp;   for(j = 1; j < n; j++)   {     for(i = 0; i < (n - j); i++)     {       if(a[i] >= a[i + 1])       {         //Swap a[i], a[i+1]       }     }   } }
To improvise this basic algorithm, keep track of whether a    particular pass results in any swap or not.    If not, you can break out without wasting more cycles.  void bubble_sort(int a[], int n) {   int i, j, temp;   int flag;   for(j = 1; j < n; j++) { flag = 0;     for(i = 0; i < (n - j); i++) {       if(a[i] >= a[i + 1])       { //Swap a[i], a[i+1]         flag = 1; }     }     if(flag==0)break;   } }
Selection Sort Algorithm void selection_sort(int a[], int n) {  int i, j, small, pos, temp;  for(i = 0; i < (n - 1); i++)  {    small = a[i];    pos   = i;    for(j = i + 1; j < n; j++)    {  if(a[j] < small)   {    small = a[j];    pos   = j;   }  }  temp   = a[pos];  a[pos] = a[i];  a[i]   = temp;    } }
Quick Sort Algorithm int partition(int a[], int low, int high) {   int i, j, temp, key;   key = a[low];   i   = low + 1;   j   = high;   while(1)    {     while(i < high && key >= a[i])i++;       while(key < a[j])j--;   if(i < j) {    temp = a[i];      a[i] = a[j];      a[j] = temp;    }    else  {        temp   = a[low];         a[low] = a[j];         a[j]   = temp;         return(j);         }    } }
void quicksort(int a[], int low, int high) {   int j;   if(low < high)    {     j = partition(a, low, high); quicksort(a, low, j - 1); quicksort(a, j + 1, high);    } } int main() {    // Populate the array a quicksort(a, 0, n - 1); }
Insertion Sort Algorithm void insertion_sort(int a[], int n) {   int i, j, item;    for(i = 0; i < n; i++)    {      item = a[i];      j = i - 1;      while(j >=0 && item < a[j])      {        a[j + 1] = a[j];        j--;      }      a[j + 1] = item;    } }

More Related Content

What's hot

Data Structure and Algorithms
Data Structure and Algorithms Data Structure and Algorithms
Data Structure and Algorithms
ManishPrajapati78
 
Data Structures (CS8391)
Data Structures (CS8391)Data Structures (CS8391)
Data Structures (CS8391)
Elavarasi K
 
Lecture 1 data structures and algorithms
Lecture 1 data structures and algorithmsLecture 1 data structures and algorithms
Lecture 1 data structures and algorithmsAakash deep Singhal
 
UNIT I LINEAR DATA STRUCTURES – LIST
UNIT I 	LINEAR DATA STRUCTURES – LIST 	UNIT I 	LINEAR DATA STRUCTURES – LIST
UNIT I LINEAR DATA STRUCTURES – LIST
Kathirvel Ayyaswamy
 
Arrays Data Structure
Arrays Data StructureArrays Data Structure
Arrays Data Structure
student
 
Lecture 9 - DSA - Python Data Structures
Lecture 9 - DSA - Python Data StructuresLecture 9 - DSA - Python Data Structures
Lecture 9 - DSA - Python Data StructuresHaitham El-Ghareeb
 
stack and queue array implementation in java.
stack and queue array implementation in java.stack and queue array implementation in java.
stack and queue array implementation in java.
CIIT Atd.
 
Abstract data types (adt) intro to data structure part 2
Abstract data types (adt)   intro to data structure part 2Abstract data types (adt)   intro to data structure part 2
Abstract data types (adt) intro to data structure part 2
Self-Employed
 
Python tuple
Python   tuplePython   tuple
Python tuple
Mohammed Sikander
 
Introduction to Data Structure
Introduction to Data Structure Introduction to Data Structure
Introduction to Data Structure
Prof Ansari
 
Binary Heap Tree, Data Structure
Binary Heap Tree, Data Structure Binary Heap Tree, Data Structure
Binary Heap Tree, Data Structure
Anand Ingle
 
NumPy
NumPyNumPy
Data Structures - Lecture 7 [Linked List]
Data Structures - Lecture 7 [Linked List]Data Structures - Lecture 7 [Linked List]
Data Structures - Lecture 7 [Linked List]
Muhammad Hammad Waseem
 
Introduction to NumPy (PyData SV 2013)
Introduction to NumPy (PyData SV 2013)Introduction to NumPy (PyData SV 2013)
Introduction to NumPy (PyData SV 2013)
PyData
 
Tuples in Python
Tuples in PythonTuples in Python
Tuples in Python
DPS Ranipur Haridwar UK
 
Arrays
ArraysArrays
Linked list
Linked list Linked list
Linked list
Arbind Mandal
 
Stacks overview with its applications
Stacks overview with its applicationsStacks overview with its applications
Stacks overview with its applicationsSaqib Saeed
 
Abstract Data Types
Abstract Data TypesAbstract Data Types
Abstract Data Types
karthikeyanC40
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithms
Julie Iskander
 

What's hot (20)

Data Structure and Algorithms
Data Structure and Algorithms Data Structure and Algorithms
Data Structure and Algorithms
 
Data Structures (CS8391)
Data Structures (CS8391)Data Structures (CS8391)
Data Structures (CS8391)
 
Lecture 1 data structures and algorithms
Lecture 1 data structures and algorithmsLecture 1 data structures and algorithms
Lecture 1 data structures and algorithms
 
UNIT I LINEAR DATA STRUCTURES – LIST
UNIT I 	LINEAR DATA STRUCTURES – LIST 	UNIT I 	LINEAR DATA STRUCTURES – LIST
UNIT I LINEAR DATA STRUCTURES – LIST
 
Arrays Data Structure
Arrays Data StructureArrays Data Structure
Arrays Data Structure
 
Lecture 9 - DSA - Python Data Structures
Lecture 9 - DSA - Python Data StructuresLecture 9 - DSA - Python Data Structures
Lecture 9 - DSA - Python Data Structures
 
stack and queue array implementation in java.
stack and queue array implementation in java.stack and queue array implementation in java.
stack and queue array implementation in java.
 
Abstract data types (adt) intro to data structure part 2
Abstract data types (adt)   intro to data structure part 2Abstract data types (adt)   intro to data structure part 2
Abstract data types (adt) intro to data structure part 2
 
Python tuple
Python   tuplePython   tuple
Python tuple
 
Introduction to Data Structure
Introduction to Data Structure Introduction to Data Structure
Introduction to Data Structure
 
Binary Heap Tree, Data Structure
Binary Heap Tree, Data Structure Binary Heap Tree, Data Structure
Binary Heap Tree, Data Structure
 
NumPy
NumPyNumPy
NumPy
 
Data Structures - Lecture 7 [Linked List]
Data Structures - Lecture 7 [Linked List]Data Structures - Lecture 7 [Linked List]
Data Structures - Lecture 7 [Linked List]
 
Introduction to NumPy (PyData SV 2013)
Introduction to NumPy (PyData SV 2013)Introduction to NumPy (PyData SV 2013)
Introduction to NumPy (PyData SV 2013)
 
Tuples in Python
Tuples in PythonTuples in Python
Tuples in Python
 
Arrays
ArraysArrays
Arrays
 
Linked list
Linked list Linked list
Linked list
 
Stacks overview with its applications
Stacks overview with its applicationsStacks overview with its applications
Stacks overview with its applications
 
Abstract Data Types
Abstract Data TypesAbstract Data Types
Abstract Data Types
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithms
 

Similar to Data Structure

Ch 1 intriductions
Ch 1 intriductionsCh 1 intriductions
Ch 1 intriductionsirshad17
 
Ds 111011055724-phpapp01
Ds 111011055724-phpapp01Ds 111011055724-phpapp01
Ds 111011055724-phpapp01Getachew Ganfur
 
computer notes - Linked list
computer notes - Linked listcomputer notes - Linked list
computer notes - Linked list
ecomputernotes
 
Data structure
 Data structure Data structure
Data structure
Shahariar limon
 
Fundamentals of data structures
Fundamentals of data structuresFundamentals of data structures
Fundamentals of data structuresNiraj Agarwal
 
Data Structures in C
Data Structures in CData Structures in C
Data Structures in C
Jabs6
 
1.3 Linked List.pptx
1.3 Linked List.pptx1.3 Linked List.pptx
1.3 Linked List.pptx
ssuserd2f031
 
Data Structure
Data StructureData Structure
Data Structure
HarshGupta663
 
Linear data structure concepts
Linear data structure conceptsLinear data structure concepts
Linear data structure concepts
Akila Krishnamoorthy
 
DS Module 03.pdf
DS Module 03.pdfDS Module 03.pdf
DS Module 03.pdf
SonaPathak5
 
unit 5 stack & queue.ppt
unit 5 stack & queue.pptunit 5 stack & queue.ppt
unit 5 stack & queue.ppt
SeethaDinesh
 
Linked List.pptx
Linked List.pptxLinked List.pptx
Linked List.pptx
PoonamPatil120
 
DS_LinkedList.pptx
DS_LinkedList.pptxDS_LinkedList.pptx
DS_LinkedList.pptx
msohail37
 
Linked List
Linked ListLinked List
Linked List
CHANDAN KUMAR
 
Skipl List implementation - Part 1
Skipl List implementation - Part 1Skipl List implementation - Part 1
Skipl List implementation - Part 1
Amrith Krishna
 
data structures and algorithms Unit 3
data structures and algorithms Unit 3data structures and algorithms Unit 3
data structures and algorithms Unit 3
infanciaj
 
Linked List
Linked ListLinked List
Linked List
BHARATH KUMAR
 
chapter three ppt.pptx
chapter three ppt.pptxchapter three ppt.pptx
chapter three ppt.pptx
selemonGamo
 

Similar to Data Structure (20)

Ch 1 intriductions
Ch 1 intriductionsCh 1 intriductions
Ch 1 intriductions
 
Ds 111011055724-phpapp01
Ds 111011055724-phpapp01Ds 111011055724-phpapp01
Ds 111011055724-phpapp01
 
computer notes - Linked list
computer notes - Linked listcomputer notes - Linked list
computer notes - Linked list
 
Data structure
 Data structure Data structure
Data structure
 
Fundamentals of data structures
Fundamentals of data structuresFundamentals of data structures
Fundamentals of data structures
 
Data Structures in C
Data Structures in CData Structures in C
Data Structures in C
 
Unit7 C
Unit7 CUnit7 C
Unit7 C
 
1.3 Linked List.pptx
1.3 Linked List.pptx1.3 Linked List.pptx
1.3 Linked List.pptx
 
Data Structure
Data StructureData Structure
Data Structure
 
Linear data structure concepts
Linear data structure conceptsLinear data structure concepts
Linear data structure concepts
 
DS Module 03.pdf
DS Module 03.pdfDS Module 03.pdf
DS Module 03.pdf
 
unit 5 stack & queue.ppt
unit 5 stack & queue.pptunit 5 stack & queue.ppt
unit 5 stack & queue.ppt
 
Linked List.pptx
Linked List.pptxLinked List.pptx
Linked List.pptx
 
DS Unit 2.ppt
DS Unit 2.pptDS Unit 2.ppt
DS Unit 2.ppt
 
DS_LinkedList.pptx
DS_LinkedList.pptxDS_LinkedList.pptx
DS_LinkedList.pptx
 
Linked List
Linked ListLinked List
Linked List
 
Skipl List implementation - Part 1
Skipl List implementation - Part 1Skipl List implementation - Part 1
Skipl List implementation - Part 1
 
data structures and algorithms Unit 3
data structures and algorithms Unit 3data structures and algorithms Unit 3
data structures and algorithms Unit 3
 
Linked List
Linked ListLinked List
Linked List
 
chapter three ppt.pptx
chapter three ppt.pptxchapter three ppt.pptx
chapter three ppt.pptx
 

More from Karthikeyan A K

Web 3.0
Web 3.0Web 3.0
Rails sopinoffs - Haml
Rails sopinoffs - HamlRails sopinoffs - Haml
Rails sopinoffs - Haml
Karthikeyan A K
 
Large scale web apps
Large scale web appsLarge scale web apps
Large scale web apps
Karthikeyan A K
 
The magic of ruby
The magic of rubyThe magic of ruby
The magic of ruby
Karthikeyan A K
 
C programming
C programmingC programming
C programming
Karthikeyan A K
 
ICT C++
ICT C++ ICT C++
ICT C++
Karthikeyan A K
 

More from Karthikeyan A K (6)

Web 3.0
Web 3.0Web 3.0
Web 3.0
 
Rails sopinoffs - Haml
Rails sopinoffs - HamlRails sopinoffs - Haml
Rails sopinoffs - Haml
 
Large scale web apps
Large scale web appsLarge scale web apps
Large scale web apps
 
The magic of ruby
The magic of rubyThe magic of ruby
The magic of ruby
 
C programming
C programmingC programming
C programming
 
ICT C++
ICT C++ ICT C++
ICT C++
 

Recently uploaded

Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
Elena Simperl
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Product School
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
g2nightmarescribd
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
Frank van Harmelen
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Tobias Schneck
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
RTTS
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 

Recently uploaded (20)

Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 

Data Structure

  • 2. Which of the following is faster? A binary search of an ordered set of elements in an array or a sequential search of the elements?
  • 3. The binary search is faster than the sequential search. The complexity of binary search is 'log n' whereas the complexity of a sequential search is 'n'. In a binary search, each time we proceed, we have to deal with only half of the elements of the array compared to the previous one. So the search is faster.
  • 4. List out the areas in which data structures are applied extensively?
  • 5.
  • 6. Which data structure is used to perform recursion?
  • 7. Stack. Because of its LIFO (Last In First Out) property it remembers its caller and hence knows where to return to when the function has to return. Recursion makes use of system stack for storing the return addresses of the function calls. Every recursive function has its equivalent iterative (non-recursive) function. Even when such equivalent iterative procedures are written, explicit stack is to be used.
  • 8. Tree can have duplicate values : True (or) False?
  • 9. True Tree defines the structure of an acyclic graph but does not disallow duplicates.
  • 10. The size of a Tree is the number of nodes in the Tree : True (or) False?
  • 11. True The size denotes the number of nodes, height denotes the longest path from leaf node to root node.
  • 12. Ram is told to sort a set of Data using Data structure. He has been told to use one of the following Methods Insertion Selection Exchange Linear Now Ram says a Method from the above can not be used to sort. Which is the method?
  • 13. Linear Using insertion we can perform insertion sort, using selection we can perform selection sort, and using exchange we can perform bubble sort. But no sorting method is possible using linear method; Linear is a searching method
  • 14. Ashok is told to manipulate an Arithmetic Expression. What is the data structure he will use? Linked List Tree Graph Stack
  • 15. Stack Stacks are used to evaluate the algebraic or arithmetic expressions using prefix or postfix notations
  • 16. There are 8,15,13,14 nodes in 4 different trees. Which of them could form a full binary tree? 8 15 13 14
  • 17. In general, there are 2n – 1 nodes in a full binary tree. By the method of elimination: Full binary tree contains odd number of nodes. So there cannot be a full binary tree with 8 or 14 nodes. With 13 nodes, you can form a complete binary tree but not a full binary tree. Full and complete binary trees are different All full binary trees are complete binary trees but not vice versa
  • 18. A B C D E F G Full binary Tree: A binary tree is a full binary tree if and only if: Each non leaf node has exactly two child nodes All leaf nodes have identical path length It is called full since all possible node slots are occupied
  • 19. A B C G D E F H I J K Complete binary Tree: A complete binary tree (of height h) satisfies the following conditions: Level 0 to h-1 represent a full binary tree of height h-1 One or more nodes in level h-1 may have 0, or 1 child nodes
  • 20. How many null branches are there in a binary tree with 20 nodes?
  • 21. 21 (null branches) Let’s consider a tree with 5 nodes So the total number of null nodes in a binary tree of n nodes is n+1 Null branches
  • 22. Write an algorithm to detect loop in a linked list. You are presented with a linked list, which may have a "loop" in it. That is, an element of the linked list may incorrectly point to a previously encountered element, which can cause an infinite loop when traversing the list. Devise an algorithm to detect whether a loop exists in a linked list. How does your answer change if you cannot change the structure of the list elements?
  • 23. One possible answer is to add a flag to each element of the list. You could then traverse the list, starting at the head and tagging each element as you encounter it. If you ever encountered an element that was already tagged, you would know that you had already visited it and that there existed a loop in the linked list. What if you are not allowed to alter the structure of the elements of the linked list?
  • 24. The following algorithm will find the loop: Start with two pointers ptr1 and ptr2. Set ptr1 and ptr2 to the head of the linked list. Traverse the linked list with ptr1 moving twice as fast as ptr2 (for every two elements that ptr1 advances within the list, advance ptr2 by one element). Stop when ptr1 reaches the end of the list, or when ptr1 = ptr2. If ptr1 and ptr2 are ever equal, then there must be a loop in the linked list. If the linked list has no loops, ptr1 should reach the end of the linked list ahead of ptr2
  • 25. The Operation that is not allowed in a binary search tree is Location Change Search Deletion Insertion
  • 27. Array is a type of ________________ data structure. Non Homogenous Non Linear Homogenous but not Linear Both Homogenous and Linear
  • 29. The address of a node in a data structure is called Pointer Referencer Link All the above
  • 31. The minimum number of edges in a connected cycle graph on n vertices is ________ n n + 1 n – 1 2n
  • 32. n
  • 33. The total number of passes required in a selection sort is n + 1 n – 1 n n * n
  • 35. The node that does not have any sub trees is called ___________ Null Node Zero Node Leaf Node Empty Node
  • 37. Linked List is a Static Data Structure Primitive Data Structure Dynamic Data Structure None of the above
  • 39. Which data structure is needed to convert infix notation to postfix notation. Tree Linear Linked List Stack Queue
  • 40. Stack
  • 41. If every node u in Graph (G) is adjacent to every other node v in G, it is called as _____ graph. Directed Graph Complete Graph Connected Graph Multi Graph
  • 43. Bubble sort is an example of Selection sort technique Exchange sort technique Quick sort technique None of the options
  • 45. How do you chose the best algorithm among available algorithms to solve a problem Based on space complexity Based on programming requirements Based on time complexity All the above
  • 47. Which of the following are called descendants? All the leaf nodes Parents, grandparents Root node Children, grandchildren
  • 49. Choose the limitation of an array from the below options. Memory Management is very poor Searching is slower Insertion and deletion are costlier Insertion and Deletion is not possible
  • 50. Insertion and deletion are costlier (It involves shifting rest of the elements)
  • 51. Areas where stacks are popularly used are. Subroutines Expression Handling Recursion All the above
  • 53. How would you implement queue using stack(s)?
  • 54. Use a temp stack Data In into queue Push the element into the original stack Data Out from queue Pop all the elements from stack into a temp stackpop out the first element from the temp stack
  • 55. Write a C program to compare two linked lists.
  • 56. int compare_linked_lists(struct node *q, struct node *r){ static int flag; if((q==NULL ) && (r==NULL)){ flag=1; } else{ if(q==NULL || r==NULL){ flag=0; } if(q->data!=r->data){ flag=0; } else{ compare_linked_lists(q->link,r->link); } } return(flag); }
  • 57. Write a C program to return the nth node from the end of a linked list.
  • 58. Suppose one needs to get to the 6th node from the end in the LL. First, just keep on incrementing the first pointer (ptr1) till the number of increments cross n (which is 6 in this case) STEP 1 : 1(ptr1,ptr2) -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> 10 STEP 2 : 1(ptr2) -> 2 -> 3 -> 4 -> 5 -> 6(ptr1) -> 7 -> 8 -> 9 -> 10 Now, start the second pointer (ptr2) and keep on incrementing it till the first pointer (ptr1) reaches the end of the LL. STEP 3 : 1 -> 2 -> 3 -> 4(ptr2) -> 5 -> 6 -> 7 -> 8 -> 9 -> 10 (ptr1) So here you have the 6th node from the end pointed to by ptr2!
  • 59. struct node { int data; struct node *next; }mynode; mynode * nthNode(mynode *head, int n /*pass 0 for last node*/) { mynode *ptr1,*ptr2; int count; if(!head) { return(NULL); } ptr1 = head; ptr2 = head; count = 0;
  • 60. while(count < n) { count++; if((ptr1=ptr1->next)==NULL) { //Length of the linked list less than n. Error. return(NULL); } } while((ptr1=ptr1->next)!=NULL) { ptr2=ptr2->next; } return(ptr2); }
  • 61. Write a C program to insert nodes into a linked list in a sorted fashion?
  • 62. The solution is to iterate down the list looking for the correct place to insert the new node. That could be the end of the list, or a point just before a node which is larger than the new node. Let us assume the memory for the new node has already been allocated and a pointer to that memory is being passed to this function. // Special case code for the head end void linkedListInsertSorted(struct node** headReference, struct node* newNode) { // Special case for the head end if (*headReference == NULL || (*headReference)->data >= newNode->data){ newNode->next = *headReference;
  • 63. *headReference = newNode; } else { // Locate the node before which the insertion is to happen! struct node* current = *headReference; while (current->next!=NULL && current->next->data < newNode->data){ current = current->next; } newNode->next = current->next; current->next = newNode; } }
  • 64. Write a C program to remove duplicates from a sorted linked list?
  • 65. As the linked list is sorted, we can start from the beginning of the list and compare adjacent nodes. When adjacent nodes are the same, remove the second one. There's a tricky case where the node after the next node needs to be noted before the deletion. // Remove duplicates from a sorted list void RemoveDuplicates(struct node* head) { struct node* current = head; if (current == NULL) return; // do nothing if the list is empty // Compare current node with next node while(current->next!=NULL) {
  • 66. if (current->data == current->next->data) { struct node* nextNext = current->next->next; free(current->next); current->next = nextNext; } else { current = current->next; // only advance if no deletion } } }
  • 67. Write a C program to find the depth or height of a tree.
  • 68. #define max(x,y) ((x)>(y)?(x):(y)) structBintree { int element; structBintree *left; structBintree *right; }; typedefstructBintree* Tree; int height(Tree T) { if(!T) return -1; else return (1 + max(height(T->left), height(T->right))) }
  • 69. Write C code to determine if two trees are identical
  • 70. structBintree { int element; structBintree *left; structBintree *right; }; typedefstructBintree* Tree; int CheckIdentical( Tree T1, Tree T2 ) { if(!T1 && !T2) // If both tree are NULL then return true return 1;
  • 71. else if((!T1 && T2) || (T1 && !T2)) //If either of one is NULL, return false return 0; else return ((T1->element == T2->element) && CheckIdentical(T1->left, T2-i>left) && CheckIdentical(T1->right, T2->right)); // if element of both tree are same and left and right tree is also same then both trees are same }
  • 72. Write a C code to create a copy of a Tree
  • 73. mynode *copy(mynode *root) { mynode *temp; if(root==NULL)return(NULL); temp = (mynode *) malloc(sizeof(mynode)); temp->value = root->value; temp->left = copy(root->left); temp->right = copy(root->right); return(temp); }
  • 74. Which of the following are called siblings Children of the same parent All nodes in the given path upto leaf node All nodes in a sub tree Children, Grand Children
  • 75. Children of the same parent
  • 76. Linked List can grow and shrink in size dynamically at __________ . Runtime Compile time
  • 78. The postfix of A+(B*C) is ABC*+ AB+C* ABC+* +A*BC
  • 79. ABC*+
  • 80. Data structure using sequential allocation is called Linear Data Structure Non-Linear Data Structure Non-primitive Data Structure Sequence Data Structure
  • 82. A linear list in which elements can be added or removed at either end but not in the middle is known as Tree Queue Dequeue Stack
  • 84. The average number of key comparisons done in a successful sequential search in list of length n is n+1/2 n-1/2 n/2 log n
  • 85. n+1/2
  • 86. A full binary tree with n leaves contains __________ nlog2n nodes 2^n nodes (2n-1) nodes n nodes
  • 88. If a node has positive outdegree and zero indegree, it is called a __________. Source Sink outdegreenode indegreenode
  • 90. The postfix notation for ((A+B)^C-(D-E)^(F+G)) is AB + C*DE—FG+^ ^-*+ABC –DE + FG ^+AB*C—DE^+FG ABC + CDE *-- FG +^
  • 92. If you are using C language to implement the heterogeneous linked list, what pointer type will you use?
  • 93. The heterogeneous linked list contains different data types in its nodes and we need a pointer to connect them. It is not possible to use ordinary pointers for this. So we use void pointer. Void pointer is capable of storing pointer to anytype of data (eg., integer or character) as it is a generic pointer type.
  • 94. What is heap sort?
  • 95. A Heap is an almost complete binary tree. In this tree, if the maximum level is i, then, upto the (i-1)th level should be complete. At level i, the number of nodes can be less than or equal to 2^i. If the number of nodes is less than 2^i, then the nodes in that level should be completely filled, only from left to right The property of an ascending heap is that, the root is the lowest and given any other node i, that node should be less than its left child and its right child. In a descending heap, the root should be the highest and given any other node i, that node should be greater than its left child and right child.
  • 96. To sort the elements, one should create the heap first. Once the heap is created, the root has the highest value. Now we need to sort the elements in ascending order. The root can not be exchanged with the nth element so that the item in the nth position is sorted. Now, sort the remaining (n-1) elements. This can be achieved by reconstructing the heap for (n-1) elements.
  • 97. heapsort() { n = array(); // Convert the tree into an array. makeheap(n); // Construct the initial heap. for(i=n; i>=2; i--) { swap(s[1],s[i]); heapsize--; keepheap(i); } } makeheap(n) { heapsize=n; for(i=n/2; i>=1; i--) keepheap(i); } keepheap(i) { l = 2*i; r = 2*i + 1; p = s[l]; q = s[r]; t = s[i];
  • 98. if(l<=heapsize && p->value > t->value) largest = l; else largest = i; m = s[largest]; if(r<=heapsize && q->value > m->value) largest = r; if(largest != i) { swap(s[i], s[largest]); keepheap(largest); } }
  • 99. Implement the bubble sort algorithm. How can it be improved? Write the code for selection sort, quick sort, insertion sort.
  • 100. Bubble sort algorithm void bubble_sort(int a[], int n) { int i, j, temp; for(j = 1; j < n; j++) { for(i = 0; i < (n - j); i++) { if(a[i] >= a[i + 1]) { //Swap a[i], a[i+1] } } } }
  • 101. To improvise this basic algorithm, keep track of whether a particular pass results in any swap or not. If not, you can break out without wasting more cycles. void bubble_sort(int a[], int n) { int i, j, temp; int flag; for(j = 1; j < n; j++) { flag = 0; for(i = 0; i < (n - j); i++) { if(a[i] >= a[i + 1]) { //Swap a[i], a[i+1] flag = 1; } } if(flag==0)break; } }
  • 102. Selection Sort Algorithm void selection_sort(int a[], int n) { int i, j, small, pos, temp; for(i = 0; i < (n - 1); i++) { small = a[i]; pos = i; for(j = i + 1; j < n; j++) { if(a[j] < small) { small = a[j]; pos = j; } } temp = a[pos]; a[pos] = a[i]; a[i] = temp; } }
  • 103. Quick Sort Algorithm int partition(int a[], int low, int high) { int i, j, temp, key; key = a[low]; i = low + 1; j = high; while(1) { while(i < high && key >= a[i])i++; while(key < a[j])j--; if(i < j) { temp = a[i]; a[i] = a[j]; a[j] = temp; } else { temp = a[low]; a[low] = a[j]; a[j] = temp; return(j); } } }
  • 104. void quicksort(int a[], int low, int high) { int j; if(low < high) { j = partition(a, low, high); quicksort(a, low, j - 1); quicksort(a, j + 1, high); } } int main() { // Populate the array a quicksort(a, 0, n - 1); }
  • 105. Insertion Sort Algorithm void insertion_sort(int a[], int n) { int i, j, item; for(i = 0; i < n; i++) { item = a[i]; j = i - 1; while(j >=0 && item < a[j]) { a[j + 1] = a[j]; j--; } a[j + 1] = item; } }