Paper Questions
Paper Questions
Source Code:
Q#2) Write a function to insert and delete node from a linked list.
Source Code:
void insertAtHead(node* &head, int data){
node* temp = new node(data);
if(head==NULL){
head = temp;
}
else{
temp->next = head;
head = temp;
}
}
void deleteFromBegin(node* &head){
if(head==NULL){
return;
}
node* temp = head;
head = head->next;
temp->next = NULL;
delete temp;
}
Q#3) Write a program to implement Heap Sort.
Source Code:
#include<iostream>
using namespace std;
int main(){
// We ignore -1 as we follow 1 based indexing not zero
int arr[] = {-1,5,4,3,2,1};
int size = 5;
//build heap
for(int i=size/2; i>0; i--){
heapify(arr,size,i);
}
// After Build Heap now calling HeapSort Function
heapSort(arr,size);
#include<iostream>
using namespace std;
int i = s, j = e;
// Now sort in a way that smaller element than pivot will be on left side and
larger on right
while(i<pivotIndex && j>pivotIndex){
//increment i till less than pivot found
while(arr[i]<arr[pivotIndex]){
i++;
}
//decrement j till greater than pivot found
while(arr[j]>arr[pivotIndex]){
j--;
}
// first check i and j are not cross pivotIndex,
if(i<pivotIndex && j>pivotIndex){
// if anyone of above are not satisfy than swap i and j then
increment i and decrement j
swap(arr[i++], arr[j--]);
}
}
return pivotIndex;
}
void quickSort(int* arr, int s, int e){
//base case
if(s>=e){
return;
}
// First find partition, from where the array is divided into subarrays
int p = partition(arr,s,e);
//After found out partition call quickSort for left and right subarrays
quickSort(arr,s,p-1);
quickSort(arr,p+1,e);
}
int main(){
int arr[] = {5,4,3,2,1};
int size = 5;
quickSort(arr,0,size-1);
return 0;
}