From 8fe0e6bc1409571c808c4968200f3ed0d2386f99 Mon Sep 17 00:00:00 2001 From: Salman Shah Date: Tue, 11 Oct 2016 19:15:49 +0530 Subject: [PATCH 01/12] Initial Commit Linear Search done!! --- Searching/LinearSeach.c | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 Searching/LinearSeach.c diff --git a/Searching/LinearSeach.c b/Searching/LinearSeach.c new file mode 100644 index 0000000..c82e101 --- /dev/null +++ b/Searching/LinearSeach.c @@ -0,0 +1,25 @@ +//Standard Header files for Input-Output +#include +#include + +//Linear Search function +void linearSearch(int arr[], int n, int key) { + int i; + for(i = 0; i < n; i ++) { + if(arr[i] == key) { + printf("Key found at position %d",i); + break; + } + } +} + +//Main Function +int main() { + int n; + scanf("%d",&n); + int arr[n],key,x; + printf("Enter the value of the key"); + scanf("%d",&key); + linearSearch(arr,n,key); + return 0; +} From 56e1bff2a05fb568020689cf13f2ee4626338bb7 Mon Sep 17 00:00:00 2001 From: Salman Shah Date: Tue, 11 Oct 2016 19:21:36 +0530 Subject: [PATCH 02/12] Deleted --- Sorting/README.md | 64 +++++++++++++++++++++ {Sortings => Sorting}/mergesort.c | 0 {Sortings => Sorting}/mergesortinplace(1).c | 0 {Sortings => Sorting}/randomizedquicksort.c | 0 4 files changed, 64 insertions(+) create mode 100644 Sorting/README.md rename {Sortings => Sorting}/mergesort.c (100%) rename {Sortings => Sorting}/mergesortinplace(1).c (100%) rename {Sortings => Sorting}/randomizedquicksort.c (100%) diff --git a/Sorting/README.md b/Sorting/README.md new file mode 100644 index 0000000..985c9a3 --- /dev/null +++ b/Sorting/README.md @@ -0,0 +1,64 @@ +Merge sort is a sorting technique based on divide and conquer technique. Merge sort first divides the array into equal halves and then combines them in a sorted manner + +Working of Merge Sort: + +To understand merge sort, we take an unsorted array as depicted below − +14,33,27,10,35,19,42,44 + +We know that merge sort first divides the whole array iteratively into equal halves unless the atomic values are achieved. We see here that an array of 8 items is divided into two arrays of size 4. +14,33,27,10 35,19,42,44 +Merge Sort Division : +This does not change the sequence of appearance of items in the original. Now we divide these two arrays into halves. +14,33 27,10 35,19 42,44 +Merge Sort Division +We further divide these arrays and we achieve atomic value which can no more be divided. +14 33 27 10 35 19 42 44 + +Merge Sort Division +We first compare the element for each list and then combine them into another list in sorted manner. We see that 14 and 33 are in sorted positions. We compare 27 and 10 and in the target list of 2 values we put 10 first, followed by 27. We change the order 19 and 35. 42 and 44 are placed sequentially. +Merge Sort Combine +14,33 10,27 19,35 42,44 +In next iteration of combining phase, we compare lists of two data values, and merge them into a list of found data values placing all in sorted order. +10,14,33,27 19,35,42,44 + +After final merging, the list should look like this − +10,14,19,27,33,35,42,44 +Merge Sort + + Worst case Time Complexity-O(nlogn) + +ALGORITHM: + +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 be divided. + +Step 3 − merge the smaller lists into new list in sorted order. + + + +QUICK SORT + +Quicksort is a divide and conquer algorithm. Quicksort first divides a large array into two smaller sub-arrays: the low elements and the high elements. Quicksort can then recursively sort the sub-arrays. + +The steps are: + +1.Pick an element, called a pivot, from the array. + +2.Partitioning: reorder the array so that all elements with values less than the pivot come before the pivot, while all elements with values greater than the pivot come after it (equal values can go either way). After this partitioning, the pivot is in its final position. This is called the partition operation. + +3.Recursively apply the above steps to the sub-array of elements with smaller values and separately to the sub-array of elements with greater values. + +The base case of the recursion is arrays of size zero or one, which never need to be sorted. + +The pivot selection and partitioning steps can be done in several different ways; the choice of specific implementation schemes greatly affects the algorithm's performance. + + + +RANDOMIZED QUICK SORT: + +Randomized Quick Sort is an extension of Quick Sort in which pivot element is chosen randomly.Worst case happens when randomly chosen pivot is got selected in sorted or reverse sorted order. + +In this random number generator is used and procedure is same as that for quick sort. + + diff --git a/Sortings/mergesort.c b/Sorting/mergesort.c similarity index 100% rename from Sortings/mergesort.c rename to Sorting/mergesort.c diff --git a/Sortings/mergesortinplace(1).c b/Sorting/mergesortinplace(1).c similarity index 100% rename from Sortings/mergesortinplace(1).c rename to Sorting/mergesortinplace(1).c diff --git a/Sortings/randomizedquicksort.c b/Sorting/randomizedquicksort.c similarity index 100% rename from Sortings/randomizedquicksort.c rename to Sorting/randomizedquicksort.c From ae05a7706084d8304b21b3c2689ce2879a075f65 Mon Sep 17 00:00:00 2001 From: Salman Shah Date: Tue, 11 Oct 2016 19:41:23 +0530 Subject: [PATCH 03/12] Inline Documentation added --- Searching/binarysearch.c | 35 ++++++++++++++++++---------- Searching/binarysearchrecursive.c | 36 +++++++++++++++++++---------- Searching/ternarysearch.c | 35 +++++++++++++++++----------- Searching/ternarysearchrecursive.c | 37 ++++++++++++++++++++---------- 4 files changed, 93 insertions(+), 50 deletions(-) diff --git a/Searching/binarysearch.c b/Searching/binarysearch.c index ef9540b..ec84cbf 100644 --- a/Searching/binarysearch.c +++ b/Searching/binarysearch.c @@ -1,14 +1,16 @@ -#include -#include +//Including Header files +#include +#include -int A[1000000]; - -int binarysearch(int size, int x) -{ +//Binary Search function +int binarysearch(int A[],int size, int x) { + //Variable declaration int l,r,m; - l=0; r=size; - while(l<=r) - { + l=0; + r=size; + + //Binary Search implementation + while(l<=r) { m=(l+r)/2; if(A[m] -#include +//Including the header files +#include +#include -int A[1000000]; - -int binarysearchrecursive(int l, int r, int x) -{ +//Binary Search Recursive function +int binarysearchrecursive(int A[],int l, int r, int x) { + + //Varible declaration int m; + if(l>r) return -1; + m=(l+r)/2; + if(A[m]x) - return binarysearchrecursive(l,m-1,x); - return m; + return binarysearchrecursive(A,l,m-1,x); + else + return m; } -int main() -{ +//Main function devclaration +int main() { + //Declaring a memory efficient array int i,n,k,pos; scanf("%d", &n); + int A[n]; + + //Inputting the values of the array for(i=0;i -#include +//Including Header Files +#include +#include -int A[1000000]; - -int ternarysearch(int l, int r, int x) -{ +//Ternary Search Functions +int ternarysearch(int A[], int l, int r, int x) { + //Ternary search function variables int lmid,rmid; lmid=(2*l+r)/3; rmid=(l+2*r)/3; - while(lmid!=rmid) - { + + while(lmid!=rmid) { if(x<=A[lmid]) r=lmid; else if(x>A[rmid]) l=rmid; - else - { + else { l=lmid; r=rmid; } lmid=(2*l+r)/3; rmid=(l+2*r)/3; } + if(x==A[r]) return r; return -1; } -int main() -{ +//Main Function +int main() { + + //Declaring a memory efficient array int i,n,k,pos; scanf("%d", &n); - for(i=0;i -#include +//Including the header files +#include +#include -int A[1000000]; - -int ternarysearchrecursive(int l, int r, int x) -{ +//Ternary Search Recursive Functions +int ternarysearchrecursive(int A[], int l, int r, int x) { + + //Variable declaration int lmid,rmid; + if(A[r]==x) return r; + lmid=(2*l+r)/3; rmid=(l+2*r)/3; + if(lmid==rmid && A[rmid]!=x) return -1; + if(xA[rmid]) - return ternarysearchrecursive(rmid,r,x); - return ternarysearchrecursive(lmid,rmid,x); + return ternarysearchrecursive(A,rmid,r,x); + + return ternarysearchrecursive(A,lmid,rmid,x); } -int main() -{ +//Main function +int main() { + + //Declaring a memory-efficient array int i,n,k,pos; scanf("%d", &n); + int A[n]; + + //Inputting the values of the array for(i=0;i Date: Tue, 11 Oct 2016 19:49:19 +0530 Subject: [PATCH 04/12] Inline Documentation added --- Searching/LinearSeach.c | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/Searching/LinearSeach.c b/Searching/LinearSeach.c index c82e101..9ba38d6 100644 --- a/Searching/LinearSeach.c +++ b/Searching/LinearSeach.c @@ -4,22 +4,31 @@ //Linear Search function void linearSearch(int arr[], int n, int key) { + //Variable declaration int i; + + //Linear Search for(i = 0; i < n; i ++) { if(arr[i] == key) { printf("Key found at position %d",i); break; } } + } //Main Function int main() { + //Memory-efficient array int n; scanf("%d",&n); int arr[n],key,x; + + //Key for element to search printf("Enter the value of the key"); scanf("%d",&key); + + //Function call linearSearch(arr,n,key); return 0; } From 485118ded302955b97923aff773f1c86fde5c985 Mon Sep 17 00:00:00 2001 From: Salman Shah Date: Wed, 12 Oct 2016 16:45:25 +0530 Subject: [PATCH 05/12] Sorting inline documentation added --- Sorting/README.md | 28 ++++++++----- Sorting/mergesort.c | 52 ++++++++++++++++------- Sorting/mergesortinplace(1).c | 64 ---------------------------- Sorting/mergesortinplace.c | 78 +++++++++++++++++++++++++++++++++++ Sorting/randomizedquicksort.c | 53 ++++++++++++++++-------- Sortings/README.md | 69 ------------------------------- 6 files changed, 168 insertions(+), 176 deletions(-) delete mode 100644 Sorting/mergesortinplace(1).c create mode 100644 Sorting/mergesortinplace.c delete mode 100644 Sortings/README.md diff --git a/Sorting/README.md b/Sorting/README.md index 985c9a3..b783aed 100644 --- a/Sorting/README.md +++ b/Sorting/README.md @@ -1,12 +1,18 @@ -Merge sort is a sorting technique based on divide and conquer technique. Merge sort first divides the array into equal halves and then combines them in a sorted manner +# Sorting -Working of Merge Sort: +## Merge Sort + +Merge sort is a sorting technique based on **Divide and Conquer** . Merge sort first divides the array into equal halves and then combines them in a sorted manner recursively. + +### Working of Merge Sort: To understand merge sort, we take an unsorted array as depicted below − 14,33,27,10,35,19,42,44 We know that merge sort first divides the whole array iteratively into equal halves unless the atomic values are achieved. We see here that an array of 8 items is divided into two arrays of size 4. + 14,33,27,10 35,19,42,44 + Merge Sort Division : This does not change the sequence of appearance of items in the original. Now we divide these two arrays into halves. 14,33 27,10 35,19 42,44 @@ -14,20 +20,22 @@ Merge Sort Division We further divide these arrays and we achieve atomic value which can no more be divided. 14 33 27 10 35 19 42 44 -Merge Sort Division +### Merge Sort Division + We first compare the element for each list and then combine them into another list in sorted manner. We see that 14 and 33 are in sorted positions. We compare 27 and 10 and in the target list of 2 values we put 10 first, followed by 27. We change the order 19 and 35. 42 and 44 are placed sequentially. + Merge Sort Combine + 14,33 10,27 19,35 42,44 In next iteration of combining phase, we compare lists of two data values, and merge them into a list of found data values placing all in sorted order. 10,14,33,27 19,35,42,44 After final merging, the list should look like this − -10,14,19,27,33,35,42,44 -Merge Sort +10,14,19,27,33,35,42,44 Worst case Time Complexity-O(nlogn) -ALGORITHM: +### ALGORITHM: Step 1 − if it is only one element in the list it is already sorted, return. @@ -37,13 +45,13 @@ Step 3 − merge the smaller lists into new list in sorted order. -QUICK SORT +## QUICK SORT -Quicksort is a divide and conquer algorithm. Quicksort first divides a large array into two smaller sub-arrays: the low elements and the high elements. Quicksort can then recursively sort the sub-arrays. +Quicksort is a **Divide and Conquer** algorithm. Quicksort first divides a large array into two smaller sub-arrays: the low elements and the high elements. Quicksort can then recursively sort the sub-arrays. The steps are: -1.Pick an element, called a pivot, from the array. +1.Pivot: Pick an element, called a pivot, from the array. 2.Partitioning: reorder the array so that all elements with values less than the pivot come before the pivot, while all elements with values greater than the pivot come after it (equal values can go either way). After this partitioning, the pivot is in its final position. This is called the partition operation. @@ -55,7 +63,7 @@ The pivot selection and partitioning steps can be done in several different ways -RANDOMIZED QUICK SORT: +## RANDOMIZED QUICK SORT: Randomized Quick Sort is an extension of Quick Sort in which pivot element is chosen randomly.Worst case happens when randomly chosen pivot is got selected in sorted or reverse sorted order. diff --git a/Sorting/mergesort.c b/Sorting/mergesort.c index b4df0f2..dc71df8 100644 --- a/Sorting/mergesort.c +++ b/Sorting/mergesort.c @@ -1,48 +1,68 @@ -#include -#include +//Including header files +#include +#include -void merge(int A[], int start, int end) -{ +//Merge sort function +void merge(int A[], int start, int end) { + + //Variable declaration int l,r,val,i,j,k; int C[10000]; - val=start; l=start; r=(start+end)/2+1; - while(l<=(start+end)/2 && r<=end) - { + + //Variable initialisation + val=start; + l=start; + r=(start+end)/2+1; + + while(l<=(start+end)/2 && r<=end) { if(A[l]start) - { +void mergesort(int A[], int start, int end) { + + //Mergesort-Algorithm + if(end>start) { mergesort(A,start,(start+end)/2); mergesort(A,(start+end)/2+1,end); merge(A,start,end); } + return; } -int main() -{ - int A[1000000]; +int main() { + + //Variable declaration int i,j,a,n; scanf("%d", &n); - for(i=0;i -#include - -void merge(int A[], int start, int end) -{ - int l,r,val,i,j,k,reml,remr,temp; - reml=(start+end)/2-start+1; - remr=end-start+1-reml; - val=start; l=start; r=(start+end)/2+1; - while(reml>0 && remr>0) - { - if(A[l]=l;j--) - A[j+1]=A[j]; - l++; r++; - A[val++]=temp; - } - - } - while(reml>0) - { - A[val++]=A[l++]; - reml--; - } - while(remr>0) - { - A[val++]=A[r++]; - remr--; - } - return; -} - -void mergesort(int A[], int start, int end) -{ - if(end>start) - { - mergesort(A,start,(start+end)/2); - mergesort(A,(start+end)/2+1,end); - merge(A,start,end); - } - return; -} - -int main() -{ - int A[1000000]; - int i,j,a,n; - scanf("%d", &n); - for(i=0;i +#include + +//Merge function +void merge(int A[], int start, int end) { + + //Variable declaration and initialisation + int l,r,val,i,j,k,reml,remr,temp; + reml=(start+end)/2-start+1; + remr=end-start+1-reml; + val=start; + l=start; + r=(start+end)/2+1; + + + while(reml>0 && remr>0) { + if(A[l]=l; j--) + A[j+1]=A[j]; + l++; + r++; + A[val++]=temp; + } + + } + + while(reml>0) { + A[val++]=A[l++]; + reml--; + } + + while(remr>0) { + A[val++]=A[r++]; + remr--; + } + + return; +} + +void mergesort(int A[], int start, int end) { + + if(end>start) { + mergesort(A,start,(start+end)/2); + mergesort(A,(start+end)/2+1,end); + merge(A,start,end); + } + + return; +} + +//Main Function +int main() { + //Varible declaration + int i,j,a,n; + scanf("%d", &n); + int A[n]; + + //INputting the elements of the array + for(i=0;i -#include -#include +//Include header files +#include +#include +//Include time header file for random variable +#include +//Global variable n declared int n; -int partition(int A[], int start, int end, int pivot) -{ +int partition(int A[], int start, int end, int pivot) { + + //Variable declaration int i,j,a,b,c,piv,temp; + + //Variable initialisation piv=A[pivot]; temp=A[pivot]; A[pivot]=A[end]; A[end]=temp; int place=start; - for(i=start;i<=end;i++) - { - if(A[i]<=piv) - { + + //Quick Sort implementation + for(i=start; i<=end; i++) { + if(A[i]<=piv) { temp=A[place]; A[place]=A[i]; A[i]=temp; place++; } } + return place-1; } -void quick(int A[], int start, int end) -{ +void quick(int A[], int start, int end) { + + int newpiv,random; - if(start Date: Wed, 12 Oct 2016 17:10:37 +0530 Subject: [PATCH 06/12] Arrays/Stacks inline documentation --- StacksAndQueues/README.md | 42 +++++++++++++------ StacksAndQueues/circularqueue.c | 70 ++++++++++++++++++-------------- StacksAndQueues/queue.c | 71 +++++++++++++++++++-------------- 3 files changed, 110 insertions(+), 73 deletions(-) diff --git a/StacksAndQueues/README.md b/StacksAndQueues/README.md index e5e595f..e67a50d 100644 --- a/StacksAndQueues/README.md +++ b/StacksAndQueues/README.md @@ -1,39 +1,55 @@ -##STACKS -A stack is a **last-in first-out**(LIFO) linear data structure,ie. the items are accessed from the stack -in the reversed order in which they are inserted. Elements can be added/removed from the stack only at the top. +## Stacks + +A stack is a **Last-In First-Out**(LIFO) linear data structure, ie. the items are accessed from the stack in the reversed order in which they are inserted. Elements can be added/removed from the stack only at the top. + Generally, the following two operations are performed on stacks - + * Push() - Adds an item in the stack (if the stack is not full) -* Pop() - Removes an item from the top of the stack +* Pop() - Removes an item from the top of the stack (if the stack isn't empty) + Additionally, a method can be used to check whether the stack is full/ is empty to avoid errors. -####Implementation: +### Implementation: There are two ways to implement a stack: + * Using an array * Using a linked list -For an array based stack, create an array depending on the type of variables to be stored. -Next, create a variable _top_ that refers to the top element in the stack and a variable _capacity_ that refers to the array size. -The _top_ changes from _-1_ to _capacity - 1_. We say that a stack is empty when top = -1, and the stack is full when top = capacity-1. +For an array based stack, + +-Create an array depending on the type of variables to be stored. + +- Next, create a variable _top_ that refers to the top element in the stack and a variable _capacity_ that refers to the array size. + +- The _top_ changes from _-1_ to _capacity - 1_. We say that a stack is empty when top = -1, and the stack is full when top = capacity-1. -####Use-cases - +### Use-cases - * Reversal of a word * Balancing parantheses * Hanoi Tower problem * Maze/Backtracking -##QUEUES -The queue is a _first-in first-out_ (FIFO) data structure. It is easy to visualize a queue as a line at the supermarket. +## QUEUES + +The queue is a _First-In First-Out_ (FIFO) Data Structure. It is easy to visualize a queue as a line at the supermarket. + When you go to the supermarket, customers join to the rear (end) of the line and customers come off of the line (i.e., are serviced) from the front of the line. + Generally, the following two operations are performed on queues - + * Dequeue() - Removes and returns the object at the beginning of the Queue. * Enqueue() - Adds an object to the end of the Queue. + Additional utility methods/variables for checking status can be used. -####Implementation: +###Implementation: + Queues can easily be implemented using lists/arrays. For implementing a queue, we need to keep track of two indices, _front_ and _rear_. We enqueue an item at the rear and dequeue an item from front. + If we simply increment front and rear indices, then there may be problems, the front may reach end of the array. + The solution to this problem is to increase front and rear in circular manner, by incrementing the counters modulo the size of the array. -####Use-cases - +###Use-cases - * Arithmetic Expression Evaluation * Searching algorithms diff --git a/StacksAndQueues/circularqueue.c b/StacksAndQueues/circularqueue.c index 4a2ce73..801c1e8 100644 --- a/StacksAndQueues/circularqueue.c +++ b/StacksAndQueues/circularqueue.c @@ -1,61 +1,62 @@ -#include -#include +//Includes the header files +#include +#include +//Global variable declaration int A[100000]; int head=-1; int tail=-1; - +//Size of the queue int sizeq; -void enqueue(int x) -{ - if(head==tail && head==-1) - { +//Enqueues the element passed in the function +void enqueue(int x) { + + if(head==tail && head==-1) { tail=(tail+1); head=tail; A[tail]=x; } - else - { - if((tail+1)%sizeq==head) - { + else { + if((tail+1)%sizeq==head) { tail=(tail+1)%sizeq; A[tail]=x; head++; printf("Overlap\n"); } - else - { + else { tail=(tail+1)%sizeq; A[tail]=x; } } + } -void dequeue() -{ - if(head==tail && head!=-1) - { +//Dequeues the element at the +//front of the queue +void dequeue() { + + if(head==tail && head!=-1) { head=-1; tail=-1; } - else if(head!=-1) - { + else if(head!=-1) { head=(head+1)%sizeq; } + } -void front() -{ +//Prints the element at the +//front of the queue +void front() { if(head!=-1) printf("%d\n", A[head]); } -void print() -{ +//Prints all the elements of the queue +void print() { int temphead=head; - while(temphead!=tail) - { + while(temphead!=tail) { printf("%d ", A[temphead]); temphead=(temphead+1)%sizeq; } @@ -64,24 +65,31 @@ void print() printf("\n"); } -int main() -{ +//Main function +int main() { + scanf("%d", &sizeq); int a,b,c,i,j,k; scanf("%d", &c); - while(c!=5) - { - if(c==1) - { + + //Menu driven loop to use the + //circular queue + while(c!=5) { + //Enqueue + if(c==1) { scanf("%d", &b); enqueue(b); } + if(c==2) dequeue(); + if(c==3) front(); + if(c==4) print(); + scanf("%d", &c); } } diff --git a/StacksAndQueues/queue.c b/StacksAndQueues/queue.c index 9f3da6c..066301c 100644 --- a/StacksAndQueues/queue.c +++ b/StacksAndQueues/queue.c @@ -1,80 +1,93 @@ -#include -#include +//Include header files +#include +#include -struct Queue{ +//Create Queue struct +struct Queue { int value; struct Queue* next; }; +//Initialising head and tail variables struct Queue* head=NULL; struct Queue* tail=NULL; -void enqueue(int x) -{ +//Enqueuing a variable into the array +void enqueue(int x) { + struct Queue* temp=malloc(sizeof(struct Queue)); temp->value=x; temp->next=NULL; - if(head==tail && head==NULL) - { + + if(head==tail && head==NULL) { head=temp; tail=head; } - else - { + else { head->next=temp; head=head->next; } + } -void dequeue() -{ - if(head==tail && head!=NULL) - { +//Dequeues the element in the rear +void dequeue() { + + if(head==tail && head!=NULL) { tail=NULL; head=NULL; } - else if(head!=NULL) - { + else if(head!=NULL) { tail=tail->next; } + } -void front() -{ +//Return the front element of the Queue +void front() { + if(tail!=NULL) printf("%d\n", tail->value); } -void printtot() -{ +//Prints all the elements in the Queue +void printtot() { + struct Queue* ptr=tail; - while(ptr!=NULL) - { + //Traverses throught the array + while(ptr!=NULL) { printf("%d ", ptr->value); ptr=ptr->next; } + printf("\n"); } -int main() -{ - int a; - int i,n,m; +//Main function +int main() { + //Variable initialisation + int i,n,m,a; scanf("%d", &n); - while(n!=5) - { - if(n==1) - { + + //Menu driven method + while(n!=5) { + //Enqueues the element in the Queue + if(n==1) { scanf("%d", &a); enqueue(a); } + //Dequeues the element at the front if(n==2) dequeue(); + //Returns the element at the front if(n==3) front(); + //Prints all the elements of the Queue if(n==4) printtot(); + scanf("%d", &n); } + return 0; } From 9a8407031f201b95961319c963e34b2912d95549 Mon Sep 17 00:00:00 2001 From: Salman Shah Date: Wed, 12 Oct 2016 17:22:03 +0530 Subject: [PATCH 07/12] Tries inline documentation added --- Trie/README.md | 19 +++++---- Trie/a.out | Bin 13240 -> 0 bytes Trie/numberprefixtrie.c | 88 +++++++++++++++++++++++----------------- 3 files changed, 61 insertions(+), 46 deletions(-) delete mode 100755 Trie/a.out diff --git a/Trie/README.md b/Trie/README.md index a1e5c3d..d856e7f 100644 --- a/Trie/README.md +++ b/Trie/README.md @@ -1,4 +1,6 @@ -##Tries +# Tries + +## Introduction The word trie is an infix of the word “retrieval” because the trie can find a single word in a dictionary with only a prefix of the word. The main idea of the trie data structure consists of the following parts: The trie is a tree where each node represents a single char or a prefix. @@ -6,21 +8,22 @@ A field in the trie node field, eg. value(isLeaf in the example below) will be u We mark the last node of every word as leaf node. A simple trie node structure can be as follows - ``` -struct TrieNode -{ +struct TrieNode { struct TrieNode *children[26]; //size particularly for words in the english alphabet bool isLeaf; // isLeaf is true if the node represents end of a word }; ``` -Insertion - Follow links corresponding to each character in the word to be inserted. When you +## Insertion - +Follow links corresponding to each character in the word to be inserted. When you * Encounter a null link: create new node. * Encounter the last character of the word: set isLeaf to true in that node. -Search - Follow links corresponding to each character in the key/word being searched. The key is not present in the structure if +## Search - +Follow links corresponding to each character in the key/word being searched. The key is not present in the structure if * Nodes do not exist for all characters of the key. * All nodes exist but the leaf node is not marked true. -Deletion - +## Deletion - * If key 'k' is not a prefix of any other key and nodes of key 'k' are not part of any other key then all the nodes starting from first one to the leaf node of key 'k' should be deleted. * If key 'k' is a prefix of some other key, then leaf node corresponding to key 'k' should be marked as 'not a leaf node'. @@ -42,10 +45,10 @@ Example of a trie for the words _the,there,their,answer,any,by,bye_- | r ``` -Tries can insert and find strings in ```O(L)``` time, where L represents the length of the string. +Tries can insert and find strings in `O(L)` time, where L represents the length of the string. -Use-cases - +## Use-cases - * Dictionaries * Auto-completion * IP Routing diff --git a/Trie/a.out b/Trie/a.out deleted file mode 100755 index 7d3fa1325f34b4a03d1e1eed65d82fcf9634c1ae..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 13240 zcmeHOe{fXCec!v&AtB%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m{jfOVZi=*{Jih*&)<79bZ{Msw87b_~t zdQ5Ksx9jt|cbDH%SgG`wupaXtAww9qpT9HXeoNw{TJKpLo=?swO5Z!=f2{*&eZzsP za7rC2T8@i-+eLrqx3~sYP=yXw+Tmx%u3z}H#f{U;1?f|`+HrCFd0wOEvzCADArv6p JbQpK~|1Y6T9F_n8 diff --git a/Trie/numberprefixtrie.c b/Trie/numberprefixtrie.c index beefeb4..8c7c962 100644 --- a/Trie/numberprefixtrie.c +++ b/Trie/numberprefixtrie.c @@ -1,13 +1,14 @@ +//Including header files #include #include //For storing numbers with upto 10^5 digits - char stack[10000]; int start=-1; int state; -struct Trie{ +//Struct definition +struct Trie { char val; int count; struct Trie* children[11]; @@ -15,14 +16,12 @@ struct Trie{ struct Trie* mytrie=NULL; -void delete(char A[11]) -{ - if(search(A)!=0) - { +//Function to delete element from trie +void delete(char A[11]) { + if(search(A)!=0) { int i=0; struct Trie* temp=mytrie; - while(i<11 && A[i]!='\0') - { + while(i<11 && A[i]!='\0') { temp=temp->children[A[i]-'0']; i++; } @@ -30,29 +29,31 @@ void delete(char A[11]) } } -void frees(struct Trie* temp) -{ +void frees(struct Trie* temp) { + int i; + if(temp==NULL) return; - for(i=0;i<11;i++) - { + + for(i=0;i<11;i++) { frees(temp->children[i]); } + temp=NULL; free(temp); return; } -void insert(char A[11]) -{ +//INsert element in the trie +void insert(char A[11]) { + int i,j,k; i=0; struct Trie* temp=mytrie; - while(i<11 && A[i]!='\0') - { - if(temp->children[A[i]-'0']==NULL) - { + + while(i<11 && A[i]!='\0') { + if(temp->children[A[i]-'0']==NULL) { temp->children[A[i]-'0']=malloc(sizeof(struct Trie)); for(k=0;k<10;k++) temp->children[A[i]-'0']->children[k]=NULL; @@ -63,77 +64,88 @@ void insert(char A[11]) state=1; i++; } + temp->count++; + for(k=0;k<10;k++) if(temp->children[k]!=NULL) state=1; } -int search(char A[11]) -{ +//Search function implemented +int search(char A[11]) { + struct Trie* temp=mytrie; int i=0; - while(i<11 && A[i]!='\0') - { + + while(i<11 && A[i]!='\0') { temp=temp->children[A[i]-'0']; if(temp==NULL) return 0; i++; } + return temp->count; } -void printstack() -{ +//FUnction to print Trie Stack +void printstack() { int i; - for(i=1;i<=start;i++) //We print from the 2nd element in stack as the first element just has the start "#" value which we dont need to print + + for(i=1; i<=start; i++) //We print from the 2nd element in stack as the first element just has the start "#" value which we dont need to print printf("%c",stack[i]); printf("\n"); } -void dfs(struct Trie* temp) -{ +//dfs function +void dfs(struct Trie* temp) { int i; - if(temp!=NULL) - { + if(temp!=NULL) { + start++; stack[start]=temp->val; int k=temp->count; - while(k!=0) - { + + while(k!=0) { printstack(); k--; } + for(i=0;i<10;i++) dfs(temp->children[i]); + start--; } } -int main() -{ +//Main function added +int main() { + //Variable initialisation int i,j,k,tc,n,m,a,b,c; char string[11]; scanf("%d",&tc); - for(i=0;ival='#'; - for(k=0;k<11;k++) + + for(k=0; k<11; k++) mytrie->children[k]=NULL; state=0; scanf("%d\n",&n); - for(j=0;j Date: Wed, 12 Oct 2016 17:31:00 +0530 Subject: [PATCH 08/12] Trees inline documentation added --- Trees/LeastCommonAncestor.c | 59 +++++++++++++++++++------------ Trees/SumDistBwAll2NodesInTree.c | 48 +++++++++++++++---------- Trees/a.out | Bin 9104 -> 0 bytes 3 files changed, 65 insertions(+), 42 deletions(-) delete mode 100755 Trees/a.out diff --git a/Trees/LeastCommonAncestor.c b/Trees/LeastCommonAncestor.c index 3dd6143..5ef6ef4 100644 --- a/Trees/LeastCommonAncestor.c +++ b/Trees/LeastCommonAncestor.c @@ -1,10 +1,17 @@ -#include -#include -#include +//Includes header files in the program +#include +#include +//String library in C +#include -//Use a stack to store paths when doing dfs, when we encounter a certain node, the values in the stack represent the path from the root to that node. -//We can get LCA also by storing intimes and outtimes etc +//Use a stack to store paths when doing dfs, +//+ when we encounter a certain node, the values +//+ in the stack represent the path from the root +//+ to that node. +//We can get LCA also by storing intimes +//+ and outtimes etc +//Global variable initialsiation int stack[100010]; int stackhead=-1; int afinarr[100010]; @@ -12,74 +19,80 @@ int bfinarr[100010]; int visited[100010]={0}; int a,b,acnt,bcnt; -struct LL{ +struct LL { int val; struct LL* next; }; struct LL* mylist[100010]={NULL}; -void dfs(int x) -{ +//dfs Function +void dfs(int x) { int ii; stackhead++; stack[stackhead]=x; - if(x==a) - { + if(x==a) { for(ii=0;ii<=stackhead;ii++) afinarr[ii]=stack[ii]; acnt=stackhead+1; } - if(x==b) - { + if(x==b) { for(ii=0;ii<=stackhead;ii++) bfinarr[ii]=stack[ii]; bcnt=stackhead+1; } + int i; visited[x]=1; struct LL* temp=mylist[x]; - while(temp!=NULL) - { + + while(temp!=NULL) { if(visited[temp->val]==0) dfs(temp->val); temp=temp->next; } + stackhead--; } -int main() -{ +//Main function +int main() { + //Variable declaration int pp,n,c,i,j,k,q,m,af,bf; scanf("%d", &n); q=n-1; //In a tree there are n-1 edges - for(i=0;ival=b; temp->next=mylist[a]; mylist[a]=temp; + struct LL* temp2=malloc(sizeof(struct LL)); temp2->val=a; temp2->next=mylist[b]; mylist[b]=temp2; } + scanf("%d", &m); //Number of queries - for(k=0;k -#include -#include - -//Program to find sum of distances b/w all nodes using number of children of each node +//Including header files +#include +#include +//Including string library +//to perform string functions +#include +//Program to find sum of distances b/w +//all nodes using number of children of +//each node long long int visited[100100]={0}; long long int a,b,acnt,bcnt; -struct LL{ +struct LL { long long int val; long long int weight; struct LL* next; }; -long long int min(long long int a, long long int b) -{ +//Returns the minimum of two variables +long long int min(long long int a, long long int b) { if(aval]==0) children[x]+=dfs(temp->val)+1; temp=temp->next; @@ -38,39 +41,46 @@ int dfs(long long int x) //printf("%d %d", x, children[x]); } -int main() -{ +//Main function +int main() { + //Variable initialisation long long int pp,n,c,i,j,k,q,m; long long int arr3[100100][4]; scanf("%lld", &n); q=n-1; //In a tree there are n-1 edges - for(i=0;ival=b; temp->weight=c; temp->next=mylist[a]; + struct LL* temp2=malloc(sizeof(struct LL)); temp2->val=a; temp2->weight=c; temp2->next=mylist[b]; + mylist[b]=temp2; mylist[a]=temp; } + dfs(1); //Given that 1 exists in the tree, we can choose any vertex to be root long long int sum=0; - for(i=0;iiKEOtrWMa@@9(5q-q~?C5jc1aM#+^ zD0uK*|PJdZO_zR zcxT^@pA3t#XaD}2ZnEVE$xls-pt+!g_N_DE^)ukw4ER>y9z0fR1W>A68jhuKf%tV( zxYi282q$9Qjg3a4I}q)Gm`Db?cNyKiyNsSdI3jk(!_j1q=nM5FLP^mVh(u!D&>{z< z8c!O1fp8Sa&c0YwA%@u4+S1f))O&BsrRu$Fa_QAne>-}B{!vfxIIf|mW7WNPBXSt-9pGBs^tM9Qy{Oih|NCgoR1rlw3Bk@8CZRJ^hY8`0iv|d&}rZ8&(K?^yJtqVxwc1C~eT5@5|+Z^^*wS@f0@&~?pJ?bw~^E+TT9!14E&p68g**-c&@jKzc zf~pU$6DjA#@4+tT>_alhp6#4?6gHGb&v?@NE@hlA&hm)C5nI}M1c{9EIlT45nT|{8 z>LKx1KakZA)Qd*{rPR7n|7B{^#TzpI%TQ7Il!oreGyBD$|FSLP+y)Pg{>%ISm~n1m z-{be!!_%Mf{?DGYKwNop zu0W;aFr%SmrptzCa5TP_s$!Y)U?bb${3e_>`p@l~lW~5-Og{FDjDHM$70E^arGI6! zgZ}eq@!O65^Hm4yP-AnJWHwC&^;L6aPh+L}Iuu_&m7ltD{`v0nrL(?!Thbr4gT2@o$!IVB!OZ=YJo8MdcC;jAA2d#YLSFa$PLmwo+$n(E7{eElu#dgwtly5@!X2ar)?E(!f(Jc z2A{W(f}+y;LM%l->DNJjfOK8%4X&EIs^&aWIUv?8y8V__OK&8Ybg+zy{ix%Ys181t z`$>EAymH5lHWV%MgMf!n_cB`LbNN}BPqqi}^kWK#z(teG{T;jCRr8d?@A4cf^ShQG zbn33UC(CtL!(hcGmlkm~_*`{9*YYNpr^!_V{U%qX+%LTW^CR$6_?;w|pV4O#_+Ld} zpj?x#b|}t%)%45l-R7zcw>l?clPIYj>lV@V@=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d(={#;*Pr#6??N7( zRaxf!xmyKFBV!PKr3>pXLA)NtL#k}g`}j6xU!xScd~5p;DElU*$NPQx3kk3n3hZge zVYPn>7}d+%Mc|vK_L*)~pmhhUs-?UNk+#_L`JqnP59Bn>1jm#4_bvAPT|K7kpSKjq zcI@^!i#?x5+SLUI-z%`b#ho~!>^c5?ZrP#it>szmDZUgxw&(K={~mn@@(Rgn|1)G3 z+VeT+m@2=TG7E_NkD(DH=%;oyTyy6o{(ai2Zp`?5k(6XZQ*d Date: Wed, 12 Oct 2016 17:41:16 +0530 Subject: [PATCH 09/12] Segment Trees Inline Documentation added --- Searching/README.md | 9 ++++++++ SegmentTrees/README.md | 8 +++---- SegmentTrees/a.out | Bin 13416 -> 0 bytes SegmentTrees/segmenttreemin.c | 41 ++++++++++++++++++---------------- SegmentTrees/segmenttreesum.c | 38 ++++++++++++++++--------------- 5 files changed, 55 insertions(+), 41 deletions(-) create mode 100644 Searching/README.md delete mode 100755 SegmentTrees/a.out diff --git a/Searching/README.md b/Searching/README.md new file mode 100644 index 0000000..bf8c27e --- /dev/null +++ b/Searching/README.md @@ -0,0 +1,9 @@ +# Searching Algorithms + +## Linear Search + + +## Binary Search + + +## Ternary Search \ No newline at end of file diff --git a/SegmentTrees/README.md b/SegmentTrees/README.md index 5d68541..3f1b69c 100644 --- a/SegmentTrees/README.md +++ b/SegmentTrees/README.md @@ -1,6 +1,6 @@ -###**Segment Trees** +# **Segment Trees** -A segment tree is a flexible data-structure built upon an array that stores any kind of information of the subsegments(intervals) of the base array. +A Segment Tree is a flexible data-structure built upon an array that stores any kind of information of the subsegments(intervals) of the base array. These information may be, for example, the sum of the elements in the interval or the biggest/smallest value in the interval. This structure is basically maintained through three operations: @@ -11,10 +11,10 @@ This structure is basically maintained through three operations: * **Update tree**; Given `N` the size of the array, `I` the index of an element to be updated and `X` the value to update the value at `I` to, recursively updates the nodes that store any information for a interval that contains `I`. Complexity `O(log(N))`. -It is possible to see that a sum segment tree has very similar practical behavior to a Binary Indexed Tree (BIT). +It is possible to see that a sum Segment Tree has very similar practical behavior to a Binary Indexed Tree (BIT). So the main difference is that a segment tree is easily adaptable to store any information other than the sum of the interval. -###Implementation +## Implementation Segment trees, despite of being binary trees, are easiest and more efficiently maintained in an array of size `2N`. diff --git a/SegmentTrees/a.out b/SegmentTrees/a.out deleted file mode 100755 index 04059d3ba7ceaa540cffd77adcec77836cbd9ff8..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 13416 zcmeHOe{fXSb-ueRf%vsrFiwSWU`b4h;;@kbQ&HDtS7`AQ7NCL@W2g9OwYx%Fq?N3F zO9UNkk+od5im=A@WUw>oXks_xcG^bqxEaRrz$(~CO*@WgibIojW<%o63OOAdJGSaN zsNcCip5A*}xgIC|Pgk?=-1FUY&OP_Od+xjUy{kvV4ZGbg7gNd2{*V!uUlin!xH4Aw z9A_m~!1#RIOMZ2XRzWWNYDnBnLnDi>vaTc_NXB5p#X+>50 zsBQFXl6ITiL2$$eiLg3;ouwp8sqqaXM)~oToCOW?jG{3CGewo&A3=}&{HVz%1rNyj z=IfU->A#|~x$N^DiPr7gKHm}B+>uD8dpGyiY~Q?nTOidH*uvXQ_DS~Mea*Zk)sKE~ zLnNdV@!<;qw-0Fu!rTT5XlAkr$MQl(&|KF1?j(uJYnhE5=+SDyHtoY zy}pH08ndEa&aw)>z!!t1F|Cr{f?MS`S#TBOq*G$XIg*GC@s){)-tb@T~rc+&fN6^L}oU=h->-!AacaFQ{iNO z25IBp5Kmn&Il=jF5Km2?%yIr1;yuKVaQ;c+sS75DIsfOxQ`0AhIR9nhsmYUloIgQ4 zb@OC5`08KOXD>gbWv^+OpWkR~svpY@VMf))M*Wli!Ng$`)e zHn)RlnQ5<c6;w(VHF^(6TqQ z(ZWv6bxFH?)40{NwoF+oUk^K?{=R!AEBqK%E1RKMNW!thmr7p;>0X@^$Tcj{Ead`3sbSST7Pflyu^bIZBT$rlW2EsSA!PT#l&&W?}t_f|R8PM`8 z0%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4#`L-e_J#J=?_#uU5~s!Fp|W6*9~i?SF*+L7 znlP%{B1dtoO`I!>rqaBVnAG_Qhvi^`NuA;c-DHjOh}xV3Y<7pNN8TJIbFI_yI*0WS zJ-N3Zt%@a*dO8(HuRT~@{ct+ob37G~b|quI;((o_PBN#4p#2!2Zs}R-Mf4y9%$pcX zb?NQ6{d8h*wrk~pxr^7^*xQRTtY~Fl!-~8W_S1l~E^T8NE%7AzzCGOy2jZ{+BXPbs zMuV!j;kHCi%IIbMbRZuqJT8CJ3+-Pq^_$NnwXRm@m(~7N)kCt@^l31(XTF3-*a185zPMBXdnD*tARr7C!C}v*(#gu63=RHAQk|z*J?b`(>Y^XfZhw!64v#MY1 zBd*DYs(O_FN>0(E(5F4P;?4brRA{71kjQ_MQT`J~iB>68mC{%Hl18cTtY7IX{4uFt z3rb17N8l$J!RH7>B6GB6cIux2M*T|uQBwPyO%iaf$Yr+(VO+ELS@qR^s8Q+)%y}9@AQ9I>Z|@&`>ePSU zp|8%+kQ4tI0^r_S9w`^%~S&(JNm=&N;m znf$*5r@WKD3SDwh)vxwrzK^K?AJC;+t@PD&lX=6&DE&PSoMb5}O2b^$%?sq^1;5CYDM5)lSZ+tfjuhb} jw?S|t^l(A?B!1+hYQLJlC_anT-(86UB*RhYtp9%j@4wpl diff --git a/SegmentTrees/segmenttreemin.c b/SegmentTrees/segmenttreemin.c index 0a935d7..aa8e7b5 100644 --- a/SegmentTrees/segmenttreemin.c +++ b/SegmentTrees/segmenttreemin.c @@ -1,11 +1,12 @@ -#include -#include +//Header files in C +#include +#include //Segment Tree consisting of minimums -int min(int a, int b) -{ - if(bend || tillwhere=end) @@ -40,10 +39,9 @@ int rangemin(int start, int end, int fromwhere, int tillwhere, int index) } -int changeval(int start, int end, int pos, int valtoadd, int index) -{ - if(pos>=start && pos<=end) - { +//Function to change values +int changeval(int start, int end, int pos, int valtoadd, int index) { + if(pos>=start && pos<=end) { if(start!=end) mintree[index]=min(changeval(start,(start+end)/2,pos,valtoadd,index*2+1),changeval((start+end)/2+1,end,pos,valtoadd,index*2+2)); else @@ -54,14 +52,19 @@ int changeval(int start, int end, int pos, int valtoadd, int index) return mintree[index]; } -int main() -{ +//Main function declaration +int main() { + //Variable declaration and initialisation int i,j,k,a,b,c; for(i=0;i<10;i++) val[i]=i+1; + //Segment tree values maketree(0,9,0); printf("%d\n", rangemin(0,9,5,8,0)); + + //CHange segment tree values changeval(0,9,8,-5,0); printf("%d\n", rangemin(0,9,5,9,0)); + return 0; } diff --git a/SegmentTrees/segmenttreesum.c b/SegmentTrees/segmenttreesum.c index eab8138..4817e7a 100644 --- a/SegmentTrees/segmenttreesum.c +++ b/SegmentTrees/segmenttreesum.c @@ -1,29 +1,29 @@ -#include -#include +//Include header files +#include +#include //Segment tree consisting of sums +//Global variable declaration int sumtree[100000]={0}; //The tree you construct int val[100000]={0}; //Given array -int maketree(int start, int end, int index) -{ +//Makes the segment tree +int maketree(int start, int end, int index) { //Index is the position in the segment tree //Node 0 is the total sum, Node 1 is the left half sum, Node 2 is the right half sum and so on.....if n is the parent node then 2*n+1 and 2*n+2 are the left and right child nodes of the parent - if(start==end) - { + if(start==end) { sumtree[index]=val[start]; return sumtree[index]; } - else - { + else { sumtree[index]=maketree(start,(start+end)/2,index*2+1)+maketree((start+end)/2+1,end,index*2+2); return sumtree[index]; } } -int rangesum(int start, int end, int fromwhere, int tillwhere, int index) -{ +//Returnns the range of the sum +int rangesum(int start, int end, int fromwhere, int tillwhere, int index) { if(fromwhere>end || tillwhere=end) //The range you require is withing the range of current index node @@ -32,16 +32,14 @@ int rangesum(int start, int end, int fromwhere, int tillwhere, int index) return rangesum(start,(start+end)/2,fromwhere,tillwhere,index*2+1)+rangesum((start+end)/2+1,end,fromwhere,tillwhere,index*2+2); } -void changeval(int start, int end, int pos, int valtoadd, int index) -{ - if(start==end) - { +//Change value of the segment tree +void changeval(int start, int end, int pos, int valtoadd, int index) { + if(start==end) { if(pos==start) sumtree[index]+=valtoadd; return; } - if(pos>=start && pos<=end) //Since the position to add value to in the array lies within the range of the current index node which is from start to end, we need to add valtoadd to the current index node and now we proceed to the subtrees where addition of this value may be required. - { + if(pos>=start && pos<=end) { //Since the position to add value to in the array lies within the range of the current index node which is from start to end, we need to add valtoadd to the current index node and now we proceed to the subtrees where addition of this value may be required. sumtree[index]+=valtoadd; changeval(start,(start+end)/2,pos,valtoadd,index*2+1); changeval((start+end)/2+1,end,pos,valtoadd,index*2+2); @@ -51,14 +49,18 @@ void changeval(int start, int end, int pos, int valtoadd, int index) return; } -int main() -{ +//Main function declaration +int main() { + //Variable initialisation int i,j,k,a,b,c; for(i=0;i<10;i++) val[i]=i+1; + //Make a segment tree maketree(0,9,0); printf("%d\n", rangesum(0,9,0,8,0)); + //Change the value of the segment tree changeval(0,9,8,10,0); printf("%d\n", rangesum(0,9,0,9,0)); + return 0; } From c825b296a7b710b3d7c8b89890f205952b6e266b Mon Sep 17 00:00:00 2001 From: Salman Shah Date: Wed, 12 Oct 2016 18:01:08 +0530 Subject: [PATCH 10/12] AVL Trees inline documentation --- AVLTrees/a.out | Bin 13480 -> 0 bytes AVLTrees/avl.c | 107 +++++++++++++++++++++++++---------------- AVLTrees/avldelete.c | 111 +++++++++++++++++++++++-------------------- 3 files changed, 125 insertions(+), 93 deletions(-) delete mode 100755 AVLTrees/a.out diff --git a/AVLTrees/a.out b/AVLTrees/a.out deleted file mode 100755 index e90f19a25b09ff06fd8a8d0d369eefa1f9af59af..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 13480 zcmeHOe{5XEouA$HI!@xOoe;u?K(gfsH54y#2qq!?c($|Q1v!bE*g%2sys_8u9`@SW zeG3VY;?@aeZ%G@qjg(SUr6<%wr&fnf1^Moz#E=}mN~b$h6%HMT&Ub}&jZ@B)5PT5g z`+R5S`}XbgxA$v%W+A9`A zR~39Kk3{+FrZg z07ke$Kx~n}MM$z#+TOLhsUBV-Q9wgh7(T1Wf+6dD6?)|7=Pk8baF=dxzPL>5{x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/avl.c +++ b/AVLTrees/avl.c @@ -1,23 +1,28 @@ -#include -#include +//Include Header files +#include +#include -struct Node{ +//Struct to represtt a node of +//+ the AVL tree +struct Node { int val; int height; int balance; + struct Node* left; struct Node* right; }; -int maxx(int a, int b) -{ - if(b>a) +//Function that returns the +//+ maximum of two values +int maxx(int a, int b) { + if(b > a) return b; return a; } -int maxim(struct Node* a, struct Node* b) -{ +//Returns the maximum height of the AVL Tree +int maxim(struct Node* a, struct Node* b) { if(b!=NULL && a==NULL) return b->height; if(b==NULL && a!=NULL) @@ -28,8 +33,8 @@ int maxim(struct Node* a, struct Node* b) return maxx(a->height,b->height); } -int getbalance(struct Node* a, struct Node* b) -{ +//FUnction to get difference of the height +int getbalance(struct Node* a, struct Node* b) { if(a!=NULL && b!=NULL) return a->height+1-(b->height+1); if(a!=NULL) @@ -40,44 +45,56 @@ int getbalance(struct Node* a, struct Node* b) return 0; } -struct Node* leftrotate(struct Node* z) -{ +//Left rotate function in the AVL Tree +struct Node* leftrotate(struct Node* z) { + struct Node* temp=z->left; struct Node* temp2=z->right->left; struct Node* tempfin=z->right; + tempfin->left=z; + z->right=temp2; z->left=temp; + tempfin->left->height=maxim(tempfin->left->left,tempfin->left->right)+1; tempfin->height=maxim(tempfin->left,tempfin->right)+1; tempfin->left->balance=getbalance(tempfin->left->left,tempfin->left->right); tempfin->balance=getbalance(tempfin->left,tempfin->right); + return tempfin; } -struct Node* rightrotate(struct Node* z) -{ +//Right rotate function in the AVL Tree +struct Node* rightrotate(struct Node* z) { + struct Node* temp=z->right; struct Node* temp2=z->left->right; struct Node* tempfin=z->left; + tempfin->right=z; + z->left=temp2; z->right=temp; + tempfin->right->height=maxim(tempfin->right->left,tempfin->right->right)+1; tempfin->height=maxim(tempfin->right,tempfin->left)+1; tempfin->right->balance=getbalance(tempfin->right->left,tempfin->right->right); tempfin->balance=getbalance(tempfin->left,tempfin->right); + return tempfin; } -struct Node* insert(int val, struct Node* temp) -{ - if(temp==NULL) - { +struct Node* insert(int val, struct Node* temp) { + + if(temp==NULL) { + struct Node* new=malloc(sizeof(struct Node)); + new->val=val; new->left=NULL; new->right=NULL; + new->height=0; new->balance=0; //printf("%d ", val); @@ -89,45 +106,45 @@ struct Node* insert(int val, struct Node* temp) temp->right=insert(val,temp->right); temp->height=maxim(temp->left,temp->right)+1; temp->balance=getbalance(temp->left,temp->right); - if(temp->balance==-2 && (temp->right->balance==-1||temp->right->balance==0)) - { + + if(temp->balance==-2 && (temp->right->balance==-1||temp->right->balance==0)) { temp=leftrotate(temp); } - else if(temp->balance==-2 && temp->right->balance==1) - { + else if(temp->balance==-2 && temp->right->balance==1) { temp->right=rightrotate(temp->right); temp=leftrotate(temp); } - else if(temp->balance==2 && (temp->left->balance==1||temp->left->balance==0)) - { + else if(temp->balance==2 && (temp->left->balance==1||temp->left->balance==0)) { temp=rightrotate(temp); } - else if(temp->balance==2 && temp->left->balance==-1) - { + else if(temp->balance==2 && temp->left->balance==-1) { temp->left=leftrotate(temp->left); temp=rightrotate(temp); } + return temp; } -void dfs(struct Node* temp) -{ +//dfs Function +void dfs(struct Node* temp) { + if(temp->left!=NULL) dfs(temp->left); + if(temp->right!=NULL) dfs(temp->right); + printf("%d ", temp->val); } -void check(int val, struct Node* temp) -{ - if(temp==NULL) - { +void check(int val, struct Node* temp) { + + if(temp==NULL) { printf("NO\n"); return; } - if(val==temp->val) - { + + if(val==temp->val) { printf("YES\n"); return; } @@ -137,26 +154,32 @@ void check(int val, struct Node* temp) check(val,temp->right); } -int main() -{ +//Main function +int main() { + //Variable declaration struct Node* mytree=NULL; int i,n,a,k; scanf("%d", &k); - while(k!=0) - { + + //Menu driven choice to insert/check + //+ the elements in the AVL Tree + while(k!=0) { scanf("%d", &n); - if(n==1) - { + + if(n==1) { scanf("%d",&a); mytree=insert(a,mytree); } - if(n==2) - { + + if(n==2) { scanf("%d",&a); check(a,mytree); } k--; + } + printf("\n"); return 0; + } diff --git a/AVLTrees/avldelete.c b/AVLTrees/avldelete.c index 24704b8..f850c0c 100644 --- a/AVLTrees/avldelete.c +++ b/AVLTrees/avldelete.c @@ -1,25 +1,31 @@ -#include -#include +//Including header files +#include +#include +//Global variable declaration int numofelem=0; +//Struct to represent node elements +//+ of the AVL Tree struct Node{ int val; int height; int balance; + struct Node* left; struct Node* right; }; -int maxx(int a, int b) -{ - if(b>a) +// Function to return maximum of +//+ two elements +int maxx(int a, int b) { + if(b > a) return b; return a; } -int maxim(struct Node* a, struct Node* b) -{ +//Function to return maximum height +int maxim(struct Node* a, struct Node* b) { if(b!=NULL && a==NULL) return b->height; if(b==NULL && a!=NULL) @@ -30,8 +36,8 @@ int maxim(struct Node* a, struct Node* b) return maxx(a->height,b->height); } -int getbalance(struct Node* a, struct Node* b) -{ +//Function to find difference of heights +int getbalance(struct Node* a, struct Node* b) { if(a!=NULL && b!=NULL) return a->height+1-(b->height+1); if(a!=NULL) @@ -42,49 +48,54 @@ int getbalance(struct Node* a, struct Node* b) return 0; } -struct Node* leftrotate(struct Node* z) -{ +//FUnction to left rotate elements of the AVL tree +struct Node* leftrotate(struct Node* z) { struct Node* temp=z->left; struct Node* temp2=z->right->left; struct Node* tempfin=z->right; + tempfin->left=z; + z->right=temp2; z->left=temp; + tempfin->left->height=maxim(tempfin->left->left,tempfin->left->right)+1; tempfin->height=maxim(tempfin->left,tempfin->right)+1; tempfin->left->balance=getbalance(tempfin->left->left,tempfin->left->right); tempfin->balance=getbalance(tempfin->left,tempfin->right); + return tempfin; } -struct Node* rightrotate(struct Node* z) -{ +//Function to right rotate elements of the AVL tree +struct Node* rightrotate(struct Node* z) { struct Node* temp=z->right; struct Node* temp2=z->left->right; struct Node* tempfin=z->left; + tempfin->right=z; + z->left=temp2; z->right=temp; + tempfin->right->height=maxim(tempfin->right->left,tempfin->right->right)+1; tempfin->height=maxim(tempfin->right,tempfin->left)+1; tempfin->right->balance=getbalance(tempfin->right->left,tempfin->right->right); tempfin->balance=getbalance(tempfin->left,tempfin->right); + return tempfin; } -struct Node* delete(struct Node* temp, int x) -{ - if(temp->val==x && temp->left==NULL && temp->right==NULL) - { +struct Node* delete(struct Node* temp, int x) { + + if(temp->val==x && temp->left==NULL && temp->right==NULL) { numofelem--; return NULL; } else if(temp->left==NULL && temp->right==NULL) return temp; - else - { - if(temp->val==x && temp->left!=NULL) - { + else { + if(temp->val==x && temp->left!=NULL) { struct Node* temp2=temp->left; while(temp2->right!=NULL) temp2=temp2->right; @@ -93,8 +104,7 @@ struct Node* delete(struct Node* temp, int x) temp->height=maxim(temp->left,temp->right)+1; temp->balance=getbalance(temp->left,temp->right); } - else if(temp->val==x && temp->right!=NULL) - { + else if(temp->val==x && temp->right!=NULL) { struct Node* temp2=temp->right; while(temp2->left!=NULL) temp2=temp2->left; @@ -109,32 +119,28 @@ struct Node* delete(struct Node* temp, int x) temp->right=delete(temp->right,x); temp->height=maxim(temp->left,temp->right)+1; temp->balance=getbalance(temp->left,temp->right); - if(temp->balance==-2 && (temp->right->balance==-1||temp->right->balance==0)) - { + + if(temp->balance==-2 && (temp->right->balance==-1||temp->right->balance==0)) { temp=leftrotate(temp); } - else if(temp->balance==-2 && temp->right->balance==1) - { + else if(temp->balance==-2 && temp->right->balance==1) { temp->right=rightrotate(temp->right); temp=leftrotate(temp); } - else if(temp->balance==2 && (temp->left->balance==1||temp->left->balance==0)) - { + else if(temp->balance==2 && (temp->left->balance==1||temp->left->balance==0)) { temp=rightrotate(temp); } - else if(temp->balance==2 && temp->left->balance==-1) - { + else if(temp->balance==2 && temp->left->balance==-1) { temp->left=leftrotate(temp->left); temp=rightrotate(temp); } + return temp; } } -struct Node* insert(int val, struct Node* temp) -{ - if(temp==NULL) - { +struct Node* insert(int val, struct Node* temp) { + if(temp==NULL) { struct Node* new=malloc(sizeof(struct Node)); new->val=val; new->left=NULL; @@ -151,28 +157,27 @@ struct Node* insert(int val, struct Node* temp) temp->right=insert(val,temp->right); temp->height=maxim(temp->left,temp->right)+1; temp->balance=getbalance(temp->left,temp->right); - if(temp->balance==-2 && (temp->right->balance==-1 || temp->right->balance==0)) - { + + if(temp->balance==-2 && (temp->right->balance==-1 || temp->right->balance==0)) { temp=leftrotate(temp); } - else if(temp->balance==-2 && temp->right->balance==1) - { + else if(temp->balance==-2 && temp->right->balance==1) { temp->right=rightrotate(temp->right); temp=leftrotate(temp); } - else if(temp->balance==2 && (temp->left->balance==1 || temp->left->balance==0)) - { + else if(temp->balance==2 && (temp->left->balance==1 || temp->left->balance==0)) { temp=rightrotate(temp); } - else if(temp->balance==2 && temp->left->balance==-1) - { + else if(temp->balance==2 && temp->left->balance==-1) { temp->left=leftrotate(temp->left); temp=rightrotate(temp); } + return temp; } -void dfs(struct Node* temp) -{ + +//dfs Function +void dfs(struct Node* temp) { if(temp==NULL) return; if(temp->left!=NULL) @@ -182,20 +187,24 @@ void dfs(struct Node* temp) printf("%d ", temp->val); } -int main() -{ +//Main function +int main() { + //Variable declaration struct Node* mytree=NULL; int i,n,a; scanf("%d", &n); - for(i=0;i0) mytree=delete(mytree,a); From 8736b253501dd59bdc0248876da5ed4f38dc08ea Mon Sep 17 00:00:00 2001 From: Salman Shah Date: Wed, 12 Oct 2016 18:37:10 +0530 Subject: [PATCH 11/12] BIT Inline Documentation done --- BIT/README.md | 10 ++++--- BIT/a.out | Bin 13512 -> 0 bytes BIT/bit.c | 34 ++++++++++++------------ BIT/rangeupdateitspoj.c | 56 +++++++++++++++++++--------------------- 4 files changed, 51 insertions(+), 49 deletions(-) delete mode 100755 BIT/a.out diff --git a/BIT/README.md b/BIT/README.md index a063ec4..05de6f0 100644 --- a/BIT/README.md +++ b/BIT/README.md @@ -1,4 +1,4 @@ -###Binary Indexed Trees (BIT) +# Binary Indexed Trees (BIT) BIT (or Fenwick trees) are generally used in cumulative frequency and cumulative sum problems. The basic underlying principle behind BITs is that each integer can be represented as sum of powers of two. @@ -9,13 +9,15 @@ We have n boxes that contain marbles. Possible queries are 2. Sum marbles from box 1 to box i The simple solution of running a loop through the array structure has time complexity of `O(1)` for query 1 and `O(n)` for query 2. + Another strategy is to create a prefix sum array and store sum from start to i at the i’th index in this array. + Sum of a given range can now be calculated in `O(1)` time, but update operation takes `O(n)` time now. + Using Binary Indexed Trees, we can perform both operations with worst case time complexity of `O(log n)` -####Implementation -BIT can implemented as arrays. Let's assume we have n elements. A node at index y is parent of a node at index x, -iff y can be obtained by removing last set bit from binary representation of x. +## Implementation +BIT can implemented as arrays. Let's assume we have n elements. A node at index y is parent of a node at index x, if y can be obtained by removing last set bit from binary representation of x. For example, `2 -> 0010 -> 0000`,`6 -> 0110 -> 0100` Hence, the nodes which are powers of 2 (1,2,4,8...) have the root node as their parent. (For sake of simplifying visualization of the tree we can create an array of length n + 1 and use 1-indexed notation,the 0th index being a dummy root node.) diff --git a/BIT/a.out b/BIT/a.out deleted file mode 100755 index 985f43910ece06e5ac3ccecb04a950f0d5e9c678..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 13512 zcmeHOeQ;FO6~DV1LJ-(22pU9XL9KjD)&wGks%1A}@dd+2^8siJFPq&Bc{SNhci&=g zO2r1PTSS>^Ev0|d*3PuGf5;zghdK@faKKvI33gPbwKEx~wuv7tR-~z-+uynGp3U3G zu2MVwFE_kB_x$cT=iYnX{dn)b!@c3=)ozzdaB_<;2;!co2ujHM6+)|)titNW6cH3x zi@Bm4$Ru1rSwhsxF&$H;nN}z{4`>;#dbb7CyMr>r^hygBOu2z@O z_#hFnO8$;hu6Dy4W{mQ)rdtBDrUzw)X|n|jrmXix=utZ_Hu;obi>j}bUn*4lnX2xJ z8+we+<#jjo#HxFYM5e#GzkYf3^147e8CWX&P4-Flwsq~YCibHroa`ScjR7iua{l*c zy#00UZ_kD=J^$j^vn%)g@}}KXMlRs{CWH^ebe6>E7FXg*KR($#|D&^07KUGLp1prs zBcPIr+T$-$I&)JM=0278mt*pIQ$Hqh#PBJm|o`1B~np&hJ1DcTL$57%yov7G1K0#>jG^ z>)U#h2|aB_Ql_p8ea&{gCBDr_oAFd*Pb8g=r-k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tXMZ_)|NC^;i+h^!Dz6ijC9hX{12ZjQ92}3qH=xUfX$_4z$RMydhla{**!a{6y8P?BKm zfkpD?5G=>^E|k+dKJ)zEQl$C>|}*U$P710$a(@%;PJA$8EZg|{vgWj$)^~m zkAb(>&(C{LsD^erDr7yjdBCC1?`dV~V2aOUSl(eyJfZaY*^ZyTd`jOb&pgwgDt*3x z{NBfL{LNgkqO8a8uN?aPe%PVvZ*vS-zJIJgh>RB(%>hdMoX&CmPJcP|UxZF2F4pJg z{|fd09-Q({{xo!{iLB4>b-s(#|1)%H?6E$dOI0cTVby;gpIkrp>#vUb`8{`R9tx0H z-r~l2#@|ALz5V(3BEO~4$BK%w9@DeH?fU%Q)91GoxSdM;4;>;^NuFUqSNy&2^j&5 c>{Ym^jqEpGe`tOdt3S911xPN(gmKpYA0l8S?*IS* diff --git a/BIT/bit.c b/BIT/bit.c index e0bba61..7941fad 100644 --- a/BIT/bit.c +++ b/BIT/bit.c @@ -1,44 +1,46 @@ -#include +//Include header files +#include +#include +//Global variable declaration int bit[100000]={0}; //Start from the first index int n; //This is point update and range query //Stores cumilative sum -void change(int index, int val) -{ - while(index<=n) - { +//Changes index in the BIT +void change(int index, int val) { + while(index<=n) { bit[index]+=val; index+=index&((-1)*index); } } -int query(int range) -{ +//Function to check for query +int query(int range) { int ans=0; - while(range>0) - { + while(range>0) { ans+=bit[range]; range-=range&((-1)*range); } return ans; } -int main() -{ +//Main function +int main() { + //Variable declaration int i,j,k,m,a,b; scanf("%d", &n); - for(i=1;i<=n;i++) - { + //Input elements + for(i=1; i<=n; i++) { scanf("%d", &a); change(i,a); } scanf("%d", &m); - for(j=1;j<=m;j++) - { - scanf("%d%d", &a, &b); + + for(j=1;j<=m;j++) { + scanf("%d %d", &a, &b); printf("%d\n", query(b)-query(a-1)); //query of a includes a as well, we dont want to include that vertex as we want sum from a (inclusive of a) till b } return 0; diff --git a/BIT/rangeupdateitspoj.c b/BIT/rangeupdateitspoj.c index 23de1e2..b33ea63 100644 --- a/BIT/rangeupdateitspoj.c +++ b/BIT/rangeupdateitspoj.c @@ -1,58 +1,56 @@ -#include +//Include header files +#include +#include +//Global variable declaration int bit[1000000]={0}; //Start from the first index int n; //Range Update and Query at a single point //Doesnt store cumilative sum -void change(int index, int val) -{ - while(index<=n) - { +void change(int index, int val) { + while(index<=n) { bit[index]+=val; index+=index&((-1)*index); } } -int query(int range) -{ +int query(int range) { int ans=0; - while(range>0) - { + while(range>0) { ans+=bit[range]; range-=range&((-1)*range); } return ans; } -void rangechange(int a, int b, int val) -{ +void rangechange(int a, int b, int val) { change(a,val); change(b+1,(-1)*val); //Only updates elements at those values from a to b } -int main() -{ +//Main function +int main() { + //Variable declaration int i,j,k,m,a,b,c; int tc,kk; scanf("%d", &tc); - for(kk=0;kk Date: Wed, 12 Oct 2016 18:45:29 +0530 Subject: [PATCH 12/12] Inline documentation changes made --- BinarySearchTrees/BinarySearchTree.c | 4 +- BinarySearchTrees/a.out | Bin 13136 -> 0 bytes BinarySearchTrees/bst.c | 111 ++++++++++++--------------- 3 files changed, 49 insertions(+), 66 deletions(-) delete mode 100755 BinarySearchTrees/a.out diff --git a/BinarySearchTrees/BinarySearchTree.c b/BinarySearchTrees/BinarySearchTree.c index 530ede1..10b4676 100644 --- a/BinarySearchTrees/BinarySearchTree.c +++ b/BinarySearchTrees/BinarySearchTree.c @@ -1,5 +1,5 @@ -#include -#include +#include +#include // create a struct called `Node` that holds an int diff --git a/BinarySearchTrees/a.out b/BinarySearchTrees/a.out deleted file mode 100755 index 7ad48ab7e1198f0fe094a66d89b598b0419b3582..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 13136 zcmeHNeQ;dWb-%kSVfkw%fdK`jcnNkRl4xTaWQy9ZJ<(grYa^nN6z|rKj7)@SHA`Cxmu?0hpkRbI}Y??wX z_>~(hlA#a*$sjw5wdPhy0(MG-p{C;KRFLh6B)bM>*P!eej;p{Ja(9qr0ryH^86 zv_?R*$a4{rF14L+ry_)(s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1E6RhhoUqsm|Q-E4DZUglfw6 zyg#2%{d1n&zdQe<%D$N$^1fVMr~$<%d&VP((PpAFphr(O2^-#GtIewYmvblbn^vghZUhFZ&D6$hs5`T8kRi~{lFP{YN3 z4&wjI-TH3&r?9Pd*z^0LI`#j(Ti;E;4qK`}_s`EIfsbfU`*Iq4Y|qbM{Qv(rIY;C1 z$^G*jSP0u2EKHxb9ev$3odh$H2?qr diff --git a/BinarySearchTrees/bst.c b/BinarySearchTrees/bst.c index bef4259..3d412c7 100644 --- a/BinarySearchTrees/bst.c +++ b/BinarySearchTrees/bst.c @@ -1,13 +1,16 @@ -#include -#include +//Including Header files +#include +#include -struct Node{ +//Struct to dfine a node in the tree +struct Node { int val; struct Node* left; struct Node* right; }; -struct Queue{ +//Queue using a struct +struct Queue { struct Node* value; struct Queue* next; }; @@ -18,22 +21,18 @@ int state; struct Node* mytree=NULL; -struct Node* delete(struct Node* temp, int x) -{ +struct Node* delete(struct Node* temp, int x) { if(temp->val==x && temp->left==NULL && temp->right==NULL) return NULL; - else - { - if(temp->val==x && temp->left!=NULL) - { + else { + if(temp->val==x && temp->left!=NULL) { struct Node* temp2=temp->left; while(temp2->right!=NULL) temp2=temp2->right; temp->val=temp2->val; temp->left=delete(temp->left,temp2->val); } - else if(temp->val==x && temp->right!=NULL) - { + else if(temp->val==x && temp->right!=NULL) { struct Node* temp2=temp->right; while(temp2->left!=NULL) temp2=temp2->left; @@ -48,42 +47,36 @@ struct Node* delete(struct Node* temp, int x) } } -void preorder(struct Node* temp) -{ - if(temp!=NULL) - { +//Function to traverse in a pre-order manner +void preorder(struct Node* temp) { + if(temp!=NULL) { printf("%d ", temp->val); preorder(temp->left); preorder(temp->right); } } -void postorder(struct Node* temp) -{ - if(temp!=NULL) - { +//Function to traverse in post-order +void postorder(struct Node* temp) { + if(temp!=NULL) { postorder(temp->left); postorder(temp->right); printf("%d ", temp->val); } } -void inorder(struct Node* temp) -{ - if(temp!=NULL) - { +//Function to traverse inorder +void inorder(struct Node* temp) { + if(temp!=NULL) { inorder(temp->left); printf("%d ", temp->val); inorder(temp->right); } } -void checktree(struct Node* temp, int min, int max) -{ - if(temp!=NULL) - { - if(temp->val>=min && temp->val<=max) - { +void checktree(struct Node* temp, int min, int max) { + if(temp!=NULL) { + if(temp->val>=min && temp->val<=max) { checktree(temp->left,min,temp->val); checktree(temp->right,temp->val+1,max); } @@ -92,43 +85,39 @@ void checktree(struct Node* temp, int min, int max) } } -int find(int x) -{ +//Function to find an element in the BST +int find(int x) { struct Node* temp=mytree; - while(temp!=NULL) - { + while(temp!=NULL) { if(temp->val==x) return 1; if(temp->valright; else temp=temp->left; + } + return 0; } -void insert(int x) -{ +//Function to insert an element in the BST +void insert(int x) { struct Node* temp=mytree; struct Node* temp2=malloc(sizeof(struct Node)); temp2->left=NULL; temp2->right=NULL; temp2->val=x; - if(mytree==NULL) - { + if(mytree==NULL) { mytree=temp2; } - else - { - while(1) - { - if(temp->val>=x && temp->left==NULL) - { + else { + while(1) { + if(temp->val>=x && temp->left==NULL) { temp->left=temp2; break; } - else if(temp->valright==NULL) - { + else if(temp->valright==NULL) { temp->right=temp2; break; } @@ -141,44 +130,38 @@ void insert(int x) return; } -int main() -{ +//Main function +int main() { + //Variable initialisation int x,y,z; scanf("%d", &x); - while(x!=6) - { - if(x==1) - { + //Menu-driven to get a function of BST + while(x!=6) { + if(x==1) { scanf("%d", &y); insert(y); } - if(x==2) - { + if(x==2) { scanf("%d", &y); printf("%d\n", find(y)); } - if(x==3) - { + if(x==3) { inorder(mytree); printf("\n"); } - if(x==4) - { + if(x==4) { preorder(mytree); printf("\n"); } - if(x==5) - { + if(x==5) { postorder(mytree); printf("\n"); } - if(x==7) - { + if(x==7) { scanf("%d", &y); mytree=delete(mytree,y); } - if(x==8) - { + if(x==8) { state=0; checktree(mytree,-100000000,1000000000); if(state==0)