├── .gitignore ├── Backtracking └── N-Queen Problem │ ├── Eight-queen.png │ ├── Eight-queens-animation.gif │ ├── README.md │ └── n-queen.c ├── Data Structure ├── BST │ ├── README.md │ ├── binary_serarch_tree.c │ └── images │ │ ├── binary_search_tree.jpg │ │ ├── bst-remove-case-1.png │ │ ├── bst-remove-case-2-1.png │ │ ├── bst-remove-case-2-2.png │ │ ├── bst-remove-case-2-3.png │ │ ├── bst-remove-case-3-3.png │ │ ├── bst-remove-case-3-4.png │ │ ├── bst-remove-case-3-5.png │ │ ├── bst-remove-case-3-6.png │ │ ├── bst_insert.png │ │ └── bst_search.png ├── Binary Heap │ ├── README.md │ ├── binary_heap.c │ ├── complete.bmp │ ├── heap.bmp │ ├── max_heap_deletion_animation.gif │ └── max_heap_insertion.gif ├── Queue │ ├── README.md │ ├── queue.svg │ ├── queue_using_array.c │ └── queue_using_linked_list.c └── Stack │ ├── README.md │ ├── stack.svg │ ├── stack_using_array.c │ └── stack_using_linked_list.c ├── README.md └── Sorting ├── Bubble Sort ├── README.md ├── bubble-sort.png └── bubble_sort.c ├── Insertion Sort ├── README.md ├── insertion_sort.c └── insertion_sort.jpg ├── README.md ├── Selection Sort ├── README.md ├── selection_sort.c └── selection_sort.jpg └── sorting_algorithms.png /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Backtracking/N-Queen Problem/Eight-queen.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Algorithm-archive/Learn-Data_Structure-Algorithm-by-C/e9922b7652ca29ecfc17d6fff4af0c2a2e5225c6/Backtracking/N-Queen Problem/Eight-queen.png -------------------------------------------------------------------------------- /Backtracking/N-Queen Problem/Eight-queens-animation.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Algorithm-archive/Learn-Data_Structure-Algorithm-by-C/e9922b7652ca29ecfc17d6fff4af0c2a2e5225c6/Backtracking/N-Queen Problem/Eight-queens-animation.gif -------------------------------------------------------------------------------- /Backtracking/N-Queen Problem/README.md: -------------------------------------------------------------------------------- 1 | ## N-queen problem 2 | 3 | The **N queens puzzle** is the problem of placing N chess queens on an n×n chessboard so that no two queens threaten each other. Thus, a solution requires that no two queens share the same row, column, or diagonal. Solutions exist for all natural numbers n with the exception of n=2 and n=3. 4 | 5 | ![N-queen Problem ](Eight-queen.png) 6 | 7 | *The only symmetrical solution to the eight queens puzzle (except for rotations and reflections of itself)* 8 | 9 | 10 | ### Backtracking Algorithm 11 | The idea is to place queens one by one in different rows, starting from the first row. When we place a queen in a row, we check for clashes with already placed queens. In the current row, if we find a column for which there is no clash, we mark this row and column as part of the solution. If we do not find such a column due to clashes then we backtrack. 12 | 13 | This algorithm of solving this problem is known as a 'depth-first search' or 'Backtracking' approach. This is much better than the naive approach where all possible arrangements of the queens need to produce and then check if it is a valid solution. 14 | 15 | ![N-queen Problem visualization ](Eight-queens-animation.gif) 16 | 17 | ### More on this topic 18 | - https://en.wikipedia.org/wiki/Eight_queens_puzzle 19 | - http://www.geeksforgeeks.org/backtracking-set-3-n-queen-problem/ 20 | - https://developers.google.com/optimization/puzzles/queens 21 | -------------------------------------------------------------------------------- /Backtracking/N-Queen Problem/n-queen.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define EMPTY 0 5 | #define QUEEN 1 6 | 7 | int queen[100][100]; 8 | int n, total_solutions; 9 | 10 | void initializeBoard(int n) 11 | { 12 | memset(queen, EMPTY, sizeof(queen)); 13 | } 14 | 15 | void printBoard() 16 | { 17 | int i,j; 18 | 19 | for(i=1;i<=n;i++) 20 | { 21 | for(j=1;j<=n;j++) 22 | { 23 | printf("%c ", queen[i][j] ? 'Q' : '-'); 24 | } 25 | printf("\n"); 26 | } 27 | printf("\n"); 28 | } 29 | 30 | int haveConflict(int row, int col) 31 | { 32 | int i,j; 33 | 34 | //check the column positions above this position 35 | for(i=1;i0 && j>0;i--,j--) 43 | { 44 | if(queen[i][j] == QUEEN) 45 | return 1; 46 | } 47 | 48 | //check upper right diagonal 49 | for(i=row-1,j=col+1;i>0 && j<=n;i--,j++) 50 | { 51 | if(queen[i][j] == QUEEN) 52 | return 1; 53 | } 54 | 55 | return 0; 56 | } 57 | 58 | //target is to place one queen in each row so that no one collides with each other 59 | //Here queen_row parameter shows the current we're going to place a Queen 60 | void backtrack(int queen_row) 61 | { 62 | int i; 63 | 64 | if(queen_row > n) 65 | { 66 | total_solutions++; 67 | printBoard(); 68 | return; 69 | } 70 | 71 | for(i=1;i<=n;i++) 72 | { 73 | if(!haveConflict(queen_row, i)) 74 | { 75 | queen[queen_row][i] = QUEEN; 76 | 77 | backtrack(queen_row + 1); 78 | 79 | queen[queen_row][i] = EMPTY; 80 | } 81 | } 82 | } 83 | 84 | int main() 85 | { 86 | printf("Enter Board size: "); 87 | scanf("%d", &n); 88 | 89 | initializeBoard(n); 90 | 91 | backtrack(1); 92 | 93 | printf("Total Solutions: %d\n", total_solutions); 94 | 95 | return 0; 96 | } 97 | -------------------------------------------------------------------------------- /Data Structure/BST/README.md: -------------------------------------------------------------------------------- 1 | # Binary Search Tree (BST) 2 | 3 | A **Binary Search Tree (BST)** is a tree in which all the nodes follow the below-mentioned properties − 4 | 5 | - The left subtree of a node contains only nodes with keys less than the node’s key. 6 | - The right subtree of a node contains only nodes with keys greater than the node’s key. 7 | - The left and right subtree each must also be a binary search tree. 8 | 9 | BST is a collection of nodes arranged in a way where they maintain BST properties. Each node has a key and an associated value. While searching, the desired key is compared to the keys in BST and if found, the associated value is retrieved. 10 | 11 | ![BST](./images/binary_search_tree.jpg) 12 | 13 | **Basic Operations:** 14 | 15 | Following are the basic operations of a tree − 16 | 17 | - **Search** − Searches an element in a tree. 18 | - **Insert** − Inserts an element in a tree. 19 | - **Pre-order Traversal** − Traverses a tree in a pre-order manner. 20 | - **In-order Traversal** − Traverses a tree in an in-order manner. 21 | - **Post-order Traversal** − Traverses a tree in a post-order manner. 22 | 23 | ##### Search Operation 24 | 25 | To search a given key in Binary Search Tree, we first compare it with root, if the key is present at root, we return root. If key is greater than root’s key, we recur for right subtree of root node. Otherwise we recur for left subtree. 26 | 27 | ![BST Search](./images/bst_search.png) 28 | 29 | ##### Insertion 30 | 31 | Whenever an element is to be inserted, first locate its proper location. Start searching from the root node, then if the data is less than the key value, search for the empty location in the left subtree and insert the data. Otherwise, search for the empty location in the right subtree and insert the data. 32 | 33 | ![BST Insert](./images/bst_insert.png) 34 | 35 | ##### Deletion 36 | 37 | When we delete a node, there possibilities arise. 38 | - **Node to be deleted is leaf:** Simply remove from the tree. 39 | 40 | ![BST Remove-1](./images/bst-remove-case-1.png) 41 | 42 | - **Node to be deleted has only one child:** Copy the child to the node and delete the child. 43 | 44 | ![BST Remove-2-1](./images/bst-remove-case-2-1.png) 45 | ![BST Remove-2-2](./images/bst-remove-case-2-2.png) 46 | ![BST Remove-2-3](./images/bst-remove-case-2-3.png) 47 | 48 | - **Node to be deleted has two children:** Find inorder successor of the node. Copy contents of the inorder successor to the node and delete the inorder successor. 49 | 50 | ![BST Remove-3-3](./images/bst-remove-case-3-3.png) 51 | ![BST Remove-3-4](./images/bst-remove-case-3-4.png) 52 | ![BST Remove-3-5](./images/bst-remove-case-3-5.png) 53 | ![BST Remove-3-6](./images/bst-remove-case-3-6.png) 54 | 55 | #### Complexity Analysis 56 | - Insertion - O(log n) 57 | - Deletion - O(log n) 58 | - Access - O(log n) 59 | - Search - O(log n) 60 | 61 | ### More on this topic 62 | - https://www.tutorialspoint.com/data_structures_algorithms/binary_search_tree.htm 63 | - http://www.algolist.net/Data_structures/Binary_search_tree 64 | - http://quiz.geeksforgeeks.org/binary-search-tree-set-1-search-and-insertion/ 65 | - http://quiz.geeksforgeeks.org/binary-search-tree-set-2-delete/ 66 | - https://en.wikibooks.org/wiki/Data_Structures/Trees#Binary_Search_Trees 67 | -------------------------------------------------------------------------------- /Data Structure/BST/binary_serarch_tree.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | typedef struct 5 | { 6 | int number; 7 | struct node *leftChild; 8 | struct node *rightChild; 9 | 10 | } node; 11 | 12 | node* root = NULL; 13 | 14 | void insertNode(int value) 15 | { 16 | node* tempNode; 17 | node* currentNode = NULL; 18 | 19 | tempNode = (node *) malloc(sizeof(node)); 20 | tempNode->number = value; 21 | tempNode->leftChild = NULL; 22 | tempNode->rightChild = NULL; 23 | 24 | 25 | if(root == NULL) //For the very first call 26 | { 27 | root = tempNode; 28 | } 29 | else 30 | { 31 | currentNode = root; 32 | 33 | while(1) 34 | { 35 | if(value <= currentNode->number) 36 | { 37 | if(currentNode->leftChild == NULL) 38 | { 39 | currentNode->leftChild = tempNode; 40 | break; 41 | } 42 | 43 | currentNode = currentNode->leftChild; 44 | } 45 | else 46 | { 47 | if(currentNode->rightChild == NULL) 48 | { 49 | currentNode->rightChild = tempNode; 50 | break; 51 | } 52 | 53 | currentNode = currentNode->rightChild; 54 | } 55 | } 56 | } 57 | } 58 | 59 | void inOrderPrint(node *rootNode) // InOrder Traversal (left-root-right) 60 | { 61 | if(rootNode==NULL) 62 | return; 63 | 64 | inOrderPrint(rootNode->leftChild); 65 | 66 | printf("%d ", rootNode->number); 67 | 68 | inOrderPrint(rootNode->rightChild); 69 | } 70 | 71 | void preOrderPrint(node *rootNode) // PreOrder Traversal (root-left-right) 72 | { 73 | if(rootNode==NULL) 74 | return; 75 | 76 | printf("%d ", rootNode->number); 77 | 78 | preOrderPrint(rootNode->leftChild); 79 | 80 | preOrderPrint(rootNode->rightChild); 81 | } 82 | 83 | void postOrderPrint(node *rootNode) // PostOrder Traversal (left-right-root) 84 | { 85 | if(rootNode==NULL) 86 | return; 87 | 88 | postOrderPrint(rootNode->leftChild); 89 | 90 | postOrderPrint(rootNode->rightChild); 91 | 92 | printf("%d ", rootNode->number); 93 | } 94 | 95 | node* searchOnTree(int value) 96 | { 97 | node* currentNode = root; 98 | 99 | while(currentNode != NULL) 100 | { 101 | if(value == currentNode->number) 102 | { 103 | break; 104 | } 105 | else if(value <= currentNode->number) 106 | currentNode = currentNode->leftChild; 107 | else 108 | currentNode = currentNode->rightChild; 109 | } 110 | 111 | return currentNode; 112 | } 113 | 114 | node * findMinimum(node *currentNode) 115 | { 116 | if(currentNode->leftChild==NULL) 117 | return currentNode; 118 | 119 | return findMinimum(currentNode->leftChild); 120 | } 121 | 122 | node * deleteNode(node *currentNode, int value) 123 | { 124 | if(currentNode==NULL) // empty tree 125 | return NULL; 126 | else if(value < currentNode->number) // value is less than node's number. so go to left subtree 127 | currentNode->leftChild = deleteNode(currentNode->leftChild, value); 128 | else if(value > currentNode->number) // value is greater than node's number. so go to right subtree 129 | currentNode->rightChild = deleteNode(currentNode->rightChild, value); 130 | else // node found. Let's delete it! 131 | { 132 | //node has no child 133 | if(currentNode->leftChild == NULL && currentNode->rightChild == NULL) 134 | { 135 | currentNode = NULL; 136 | } 137 | else if(currentNode->leftChild == NULL) // node has only right child 138 | { 139 | currentNode = currentNode->rightChild; 140 | } 141 | else if(currentNode->rightChild == NULL) // node has only left child 142 | { 143 | currentNode = currentNode->leftChild; 144 | } 145 | else // node has two children 146 | { 147 | node *tempNode = findMinimum(currentNode->rightChild); 148 | currentNode->number = tempNode->number; 149 | currentNode->rightChild = deleteNode(currentNode->rightChild, tempNode->number); 150 | } 151 | 152 | } 153 | 154 | return currentNode; 155 | } 156 | 157 | 158 | int main() 159 | { 160 | int i, value; 161 | //int numbers[] = {45, 54, 40, 49, 38, 70, 30, 39, 41, 45, 44}; 162 | int numbers[] = {5, 2, 17, 6, 20}; 163 | int numbers_length = sizeof(numbers)/sizeof(numbers[0]); 164 | node* node_to_delete; 165 | 166 | for(i=0;i 4 | 5 | #define SZ 100 6 | 7 | int getParentPos(int pos, int lastPos) 8 | { 9 | if(pos<=0 || pos >= lastPos) 10 | return -1; 11 | 12 | return (int) (pos-1)/2; 13 | } 14 | 15 | int getLeftChildPos(int pos, int lastPos) 16 | { 17 | int left = (2*pos) + 1; 18 | 19 | if(left >= lastPos) 20 | return -1; 21 | 22 | return left; 23 | } 24 | 25 | int getRightChildPos(int pos, int lastPos) 26 | { 27 | int right = (2*pos) + 2; 28 | 29 | if(right >= lastPos) 30 | return -1; 31 | 32 | return right; 33 | } 34 | 35 | int getMaximum(int heap[], int lastPos) 36 | { 37 | if(lastPos <= 0) 38 | return -1; 39 | 40 | return heap[0]; 41 | } 42 | 43 | void swapElem(int heap[], int pos1, int pos2) 44 | { 45 | int tmp; 46 | 47 | tmp = heap[pos1]; 48 | heap[pos1] = heap[pos2]; 49 | heap[pos2] = tmp; 50 | } 51 | 52 | void heapifyDown(int heap[], int pos, int lastPos) 53 | { 54 | int heapSize = lastPos; 55 | while(1) 56 | { 57 | int left = getLeftChildPos(pos, heapSize); 58 | int right = getRightChildPos(pos, heapSize); 59 | int maxValPos; 60 | 61 | if(left != -1 && heap[left] > heap[pos]) 62 | maxValPos = left; 63 | else 64 | maxValPos = pos; 65 | 66 | if(right != -1 && heap[right] > heap[maxValPos]) 67 | maxValPos = right; 68 | 69 | if(maxValPos != pos) 70 | { 71 | swapElem(heap, pos, maxValPos); 72 | } 73 | else 74 | break; 75 | 76 | pos = maxValPos; 77 | } 78 | } 79 | 80 | void heapifyUp(int heap[], int lastPos) 81 | { 82 | int pos = lastPos; 83 | while(pos>0) 84 | { 85 | int parent = getParentPos(pos, lastPos); 86 | if(parent == -1) 87 | break; 88 | 89 | if(heap[parent] < heap[pos]) 90 | { 91 | swapElem(heap, parent, pos); 92 | pos = parent; 93 | } 94 | else 95 | break; 96 | } 97 | } 98 | 99 | 100 | int main() 101 | { 102 | int heap[SZ]; 103 | int value, num_of_elem = 0, action; 104 | 105 | while(1) 106 | { 107 | printf("Enter Action: \n 1.Insert \n 2.Get Max Value \n 3.Exit\n"); 108 | scanf("%d", &action); 109 | 110 | if(action == 1) //Insertion 111 | { 112 | printf("Enter Value: "); 113 | scanf("%d", &value); 114 | heap[num_of_elem] = value; 115 | 116 | heapifyUp(heap, num_of_elem); 117 | num_of_elem++; 118 | } 119 | else if(action == 2) //Get and Delete Max Value 120 | { 121 | if(num_of_elem <= 0) 122 | { 123 | printf("No Elements Available\n"); 124 | continue; 125 | } 126 | 127 | int maxVal = getMaximum(heap, num_of_elem); 128 | heap[0] = heap[num_of_elem - 1]; 129 | 130 | printf("Max Val: %d\n", maxVal); 131 | num_of_elem--; 132 | 133 | heapifyDown(heap, 0, num_of_elem); 134 | } 135 | else 136 | break; 137 | } 138 | 139 | return 0; 140 | } 141 | -------------------------------------------------------------------------------- /Data Structure/Binary Heap/complete.bmp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Algorithm-archive/Learn-Data_Structure-Algorithm-by-C/e9922b7652ca29ecfc17d6fff4af0c2a2e5225c6/Data Structure/Binary Heap/complete.bmp -------------------------------------------------------------------------------- /Data Structure/Binary Heap/heap.bmp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Algorithm-archive/Learn-Data_Structure-Algorithm-by-C/e9922b7652ca29ecfc17d6fff4af0c2a2e5225c6/Data Structure/Binary Heap/heap.bmp -------------------------------------------------------------------------------- /Data Structure/Binary Heap/max_heap_deletion_animation.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Algorithm-archive/Learn-Data_Structure-Algorithm-by-C/e9922b7652ca29ecfc17d6fff4af0c2a2e5225c6/Data Structure/Binary Heap/max_heap_deletion_animation.gif -------------------------------------------------------------------------------- /Data Structure/Binary Heap/max_heap_insertion.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Algorithm-archive/Learn-Data_Structure-Algorithm-by-C/e9922b7652ca29ecfc17d6fff4af0c2a2e5225c6/Data Structure/Binary Heap/max_heap_insertion.gif -------------------------------------------------------------------------------- /Data Structure/Queue/README.md: -------------------------------------------------------------------------------- 1 | # Queue 2 | 3 | **Queue** is an abstract data structure, somewhat similar to Stacks. Unlike stacks, a queue is open at both its ends. One end is always used to insert data (enqueue) and the other is used to remove data (dequeue). Queue follows First-In-First-Out methodology, i.e., the data item stored first will be accessed first. 4 | 5 | A real-world example of queue can be a single-lane one-way road, where the vehicle enters first, exits first. More real-world examples can be seen as queues at the ticket windows and bus-stops. 6 | 7 | ![Queue](queue.svg) 8 | 9 | **Basic Operations:** 10 | 11 | Queue operations may involve initializing or defining the queue, utilizing it, and then completely erasing it from the memory.. Apart from these basic stuffs, a queue is used for the following two primary operations − 12 | 13 | - **enqueue()** − add (store) an item to the queue. 14 | - **dequeue()** − remove (access) an item from the queue. 15 | 16 | To use a queue efficiently, we need to check the status of queue as well. For the same purpose, the following functionality are available too − 17 | 18 | - **peek()** − get the first data element of the queue, without removing it. 19 | - **isFull()** − check if queue is full. 20 | - **isEmpty()** − check if queue is empty. 21 | 22 | 23 | #### Complexity Analysis 24 | - Insertion - O(1) 25 | - Deletion - O(1) (If implemented with array, then deletion will take O(n) for shifting elements to rearrange the Queue) 26 | - Access - O(n) 27 | - Search - O(n) 28 | 29 | ### More on this topic 30 | - https://en.wikipedia.org/wiki/Queue_(abstract_data_type) 31 | - https://www.tutorialspoint.com/data_structures_algorithms/dsa_queue.htm 32 | - https://en.wikibooks.org/wiki/Data_Structures/Stacks_and_Queues 33 | -------------------------------------------------------------------------------- /Data Structure/Queue/queue.svg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Algorithm-archive/Learn-Data_Structure-Algorithm-by-C/e9922b7652ca29ecfc17d6fff4af0c2a2e5225c6/Data Structure/Queue/queue.svg -------------------------------------------------------------------------------- /Data Structure/Queue/queue_using_array.c: -------------------------------------------------------------------------------- 1 | #include 2 | #define MAXSIZE 100 3 | 4 | int arr[MAXSIZE], last = 0; 5 | 6 | int isEmpty() 7 | { 8 | return (last<=0); //If last is reached to 0, then it is empty, return 1 else return 0 9 | } 10 | 11 | int isFull() 12 | { 13 | return (last>=MAXSIZE); //If last reached MAXSIZE then it is full, return 1, else return 0 14 | } 15 | 16 | int peek() 17 | { 18 | return arr[0]; 19 | } 20 | 21 | void enqueue(int val) 22 | { 23 | if(isFull()) 24 | printf("No more space on Queue.\n"); 25 | else 26 | arr[last++]=val; 27 | } 28 | 29 | void dequeue() 30 | { 31 | int i; 32 | 33 | if(isEmpty()) 34 | { 35 | printf("Queue is empty\n"); 36 | } 37 | else 38 | { 39 | printf("Removed element: %d\n",peek()); 40 | //Shift All element left 41 | for(i=1;i 0) 51 | { 52 | printf("Queue Elements: \n"); 53 | for(i=0;i 2 | #include 3 | 4 | typedef struct 5 | { 6 | int val; 7 | struct node* next; 8 | }node; 9 | 10 | node* head = NULL; 11 | node* tail = NULL; 12 | 13 | void printlist() 14 | { 15 | node* temp; 16 | temp=head; 17 | 18 | if(temp != NULL) 19 | { 20 | printf("Queue Elements are: "); 21 | while(temp!=NULL) 22 | { 23 | printf("%d ",temp->val); 24 | temp=temp->next; 25 | } 26 | puts(""); 27 | } 28 | } 29 | 30 | int peek() 31 | { 32 | return head->val; 33 | } 34 | 35 | int isEmpty() 36 | { 37 | return (head == NULL); 38 | } 39 | 40 | void enqueue(int x) 41 | { 42 | node* temp=(node*) malloc(sizeof(node)); 43 | temp->val=x; 44 | temp->next=NULL; 45 | 46 | if(isEmpty()) 47 | head = temp; 48 | 49 | if(tail != NULL) 50 | tail->next = temp; 51 | 52 | tail = temp; 53 | } 54 | 55 | void dequeue() 56 | { 57 | if(isEmpty()) 58 | { 59 | printf("Queue is empty\n"); 60 | } 61 | else 62 | { 63 | printf("Deleted item is: %d\n",peek()); 64 | node* temp = head; 65 | 66 | head=head->next; 67 | temp->next=NULL; 68 | if(head == NULL) 69 | tail = NULL; 70 | free(temp); 71 | } 72 | } 73 | 74 | int main() 75 | { 76 | 77 | int action, val; 78 | int exit = 0; 79 | 80 | while(!exit) 81 | { 82 | printf("Enter your choice:\n"); 83 | printf("1. Enqueue\n2. Dequeue\n3. Exit\n"); 84 | scanf("%d", &action); 85 | 86 | switch(action) 87 | { 88 | case 1: 89 | scanf("%d", &val); 90 | 91 | enqueue(val); 92 | 93 | printlist(); 94 | puts(""); 95 | break; 96 | case 2: 97 | dequeue(); 98 | 99 | printlist(); 100 | puts(""); 101 | break; 102 | case 3: 103 | exit = 1; 104 | break; 105 | } 106 | } 107 | 108 | return 0; 109 | } 110 | -------------------------------------------------------------------------------- /Data Structure/Stack/README.md: -------------------------------------------------------------------------------- 1 | # Stack 2 | 3 | A **stack** is an Abstract Data Type (ADT), commonly used in most programming languages. It is named stack as it behaves like a real-world stack, for example – a deck of cards or a pile of plates, etc. 4 | 5 | A real-world stack allows operations at one end only. For example, we can place or remove a card or plate from the top of the stack only. Likewise, Stack ADT allows all data operations at one end only. At any given time, we can only access the top element of a stack. 6 | 7 | This feature makes it LIFO data structure. LIFO stands for Last-in-first-out. Here, the element which is placed (inserted or added) last, is accessed first. In stack terminology, insertion operation is called PUSH operation and removal operation is called POP operation. 8 | 9 | 10 | Conceptually, a stack is simple: a data structure that allows adding and removing elements in a particular order. Every time an element is added, it goes on the top of the stack; the only element that can be removed is the element that was at the top of the stack. Consequently, a stack is said to have "first in last out" behavior (or "last in, first out"). The first item added to a stack will be the last item removed from a stack. 11 | 12 | ![Stack](stack.svg) 13 | 14 | **Basic Operations:** 15 | 16 | Stack operations may involve initializing the stack, using it and then de-initializing it. Apart from these basic stuffs, a stack is used for the following two primary operations − 17 | 18 | - **push()** − Pushing (storing) an element on the stack. 19 | - **pop()** − Removing (accessing) an element from the stack. 20 | 21 | To use a stack efficiently, we need to check the status of stack as well. For the same purpose, the following functionality are available too − 22 | 23 | - **peek()** − get the top data element of the stack, without removing it. 24 | - **isFull()** − check if stack is full. 25 | - **isEmpty()** − check if stack is empty. 26 | 27 | 28 | #### Complexity Analysis 29 | - Insertion - O(1) 30 | - Deletion - O(1) 31 | - Access - O(n) 32 | - Search - O(n) 33 | 34 | ### More on this topic 35 | - https://en.wikipedia.org/wiki/Stack_(abstract_data_type) 36 | - https://www.tutorialspoint.com/data_structures_algorithms/stack_algorithm.htm 37 | - https://en.wikibooks.org/wiki/Data_Structures/Stacks_and_Queues 38 | -------------------------------------------------------------------------------- /Data Structure/Stack/stack.svg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Algorithm-archive/Learn-Data_Structure-Algorithm-by-C/e9922b7652ca29ecfc17d6fff4af0c2a2e5225c6/Data Structure/Stack/stack.svg -------------------------------------------------------------------------------- /Data Structure/Stack/stack_using_array.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #define MAXSIZE 100 4 | 5 | int stack[MAXSIZE]; 6 | int top = -1; 7 | 8 | int isEmpty() 9 | { 10 | return (top == -1); //if top is -1 return 1 else return 0 11 | } 12 | 13 | int isfull() 14 | { 15 | return (top == MAXSIZE); //if top is equal to MAXSIZE return 1 else return 0 16 | } 17 | 18 | int peek() 19 | { 20 | int data = -1; 21 | if(!isEmpty()) 22 | data = stack[top]; 23 | 24 | return data; 25 | } 26 | 27 | int pop() 28 | { 29 | int data = peek(); 30 | 31 | if(data != -1) 32 | top--; 33 | 34 | return data; 35 | } 36 | 37 | void push(int data) 38 | { 39 | if(!isfull()) { 40 | top = top + 1; 41 | stack[top] = data; 42 | } 43 | else 44 | { 45 | printf("Could not insert data, Stack is full.\n"); 46 | } 47 | } 48 | 49 | int main() 50 | { 51 | 52 | int value, action; 53 | 54 | while (1) { 55 | printf("Enter Action: \n 1.Insert \n 2.Get Top Value \n 3.Exit\n"); 56 | scanf("%d", &action); 57 | 58 | if(action == 1) //Insertion 59 | { 60 | printf("Enter Value: "); 61 | scanf("%d", &value); 62 | 63 | push(value); 64 | 65 | printf("Element at top of the stack: %d\n", peek()); 66 | } 67 | else if(action ==2) 68 | { 69 | value = pop(); 70 | if(value == -1) 71 | printf("Could not retrieve data, Stack is empty.\n"); 72 | else 73 | printf("Popped value: %d\n", value); 74 | } 75 | else 76 | break; 77 | } 78 | 79 | return 0; 80 | } 81 | -------------------------------------------------------------------------------- /Data Structure/Stack/stack_using_linked_list.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | typedef struct 5 | { 6 | int val; 7 | struct node* next; 8 | }node; 9 | 10 | node* top = NULL; 11 | 12 | void push(int value) 13 | { 14 | node* tmp=(node*) malloc(sizeof(node)); //memory allocating for a node 15 | 16 | tmp->val = value; 17 | tmp->next = top; //add this new value at the end of the stack 18 | 19 | top = tmp; //now top of the stack is the new node 20 | } 21 | 22 | void pop() 23 | { 24 | node* tmp; 25 | 26 | if(top==NULL) 27 | printf("Stack is empty\n"); 28 | else 29 | { 30 | printf("popped element %d\n",top->val); 31 | tmp=top; 32 | 33 | top=top->next; //top is replaced to the next node 34 | 35 | free(tmp); //top node is deleted from the memory 36 | } 37 | } 38 | 39 | int peek() 40 | { 41 | if(top != NULL) 42 | return (int)top->val; 43 | 44 | return top; 45 | } 46 | 47 | int main() 48 | { 49 | int action,value; 50 | int exit = 0; 51 | 52 | while(!exit) 53 | { 54 | printf("Enter Action: \n 1.Insert \n 2.Get Top Value \n 3.Exit\n"); 55 | scanf("%d",&action); 56 | 57 | switch(action) 58 | { 59 | case 1: 60 | printf("Enter Value: "); 61 | scanf("%d",&value); 62 | 63 | push(value); 64 | 65 | printf("Element at top of the stack: %d\n", peek()); 66 | 67 | break; 68 | case 2: 69 | pop(); 70 | 71 | break; 72 | case 3: 73 | exit = 1; 74 | break; 75 | } 76 | } 77 | 78 | return 0; 79 | } 80 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Learn Data Structure and Algorithms by C 2 | 3 | > You need to have basic understanding of the C programming language to proceed with the codes from this repository. 4 | 5 | 6 | 7 | ## Table of Contents 8 | - [Introduction to C](#introduction) 9 | - [Data Structure](./Data%20Structure/) 10 | - [Linked List](./Data%20Structure/Linked%20List/) 11 | - [Stack](./Data%20Structure/Stack/) 12 | - [Queue](./Data%20Structure/Queue/) 13 | - [Binary Search Tree (BST)](./Data%20Structure/BST/) 14 | - Heap 15 | - Hash Table 16 | - Disjoint Set Union (Union Find) 17 | - Trie 18 | - Suffix Array 19 | - Segment Tree 20 | - Binary Indexed Tree (BIT) 21 | - Heavy Light Decomposition 22 | 23 | 24 | - [Searching](./Searching/) 25 | - [Linear Search](./Searching/Linear%20Search/) 26 | - [Binary Search](./Searching/Binary%20Search/) 27 | - [Ternary Search](./Searching/Ternary%20Search/) 28 | 29 | 30 | - [Sorting](./Sorting/) 31 | - [Selection Sort](./Sorting/Selection%20Sort/) 32 | - [Bubble Sort](./Sorting/Bubble%20Sort/) 33 | - [Insertion Sort](./Sorting/Insertion%20Sort/) 34 | - [Merge Sort](./Sorting/Merge%20Sort/) 35 | - [Quick Sort](./Sorting/Quick%20Sort/) 36 | - Bucket Sort 37 | - [Counting Sort](./Sorting/Counting%20Sort/) 38 | - Heap Sort 39 | - [Radix Sort](./Sorting/Radix%20Sort/) 40 | 41 | 42 | - Graph Algorithms 43 | - Graph Representation 44 | - Breadth First Search (BFS) 45 | - Depth First Search (DFS) 46 | - Topological Sort 47 | - Strongly Connected Components (SCC) 48 | - Minimum Spanning Tree (MST) 49 | - All Pairs Shortest Path (Floyd Warshall's Algorithm) 50 | - Single Source Shortest Path Algorithm 51 | - Djkastra's Algorithm 52 | - Bellman Ford Algorithm 53 | - Directed Acyclic Graph 54 | - Bipartite Matching 55 | - Articulation Point, Bridge 56 | - Euler Tour/Path 57 | - Hamiltonian Cycle 58 | - Stable Marriage Problem 59 | - Chinese Postman Problem 60 | - 2-satisfiability 61 | - Flow Algorithms 62 | - Maximum Flow 63 | - Minimum Cut 64 | - Min-Cost Max Flow 65 | - Maximum Bipartite Matching 66 | - Vertex Cover 67 | 68 | - Dynamic Programming 69 | - Rod Cutting 70 | - Maximum Sum (1D, 2D) 71 | - Coin Change 72 | - Longest Common Subsequence 73 | - Longest Increasing Subsequence 74 | - Matrix Multiplication 75 | - Edit Distance (Levenshtein distance) 76 | - 0/1 Knapsack 77 | - Travelling Salesman Problem 78 | - Optimal Binary Search Tree 79 | 80 | 81 | - Greedy Algorithms 82 | - Activity Selection/Task Scheduling 83 | - Huffman Coding 84 | - Knapsack Problem (Fractional Knapsack) 85 | 86 | 87 | - String Algorithms 88 | - Rabin-Karp Algorithm 89 | - Knuth-Morris-Pratt Algorithm 90 | - Z Algorithm 91 | - Aho-Korasick Algorithm 92 | - Manachers Algorithm 93 | - Boyr-Moore Algorithm 94 | 95 | 96 | - Number Theory 97 | - Greatest Common Divisor (GCD) 98 | - Longest Common Multiplier (LCM) 99 | - Euler Totient (Phi) 100 | - Prime finding(Sieve of Eratosthenes) 101 | - Prime factorization 102 | - Factorial 103 | - Fibonacci 104 | - Counting, Permutation, combination 105 | - Exponentiation 106 | - Big Mod 107 | - Euclid, Extended euclid 108 | - Josephus Problem 109 | - Farey Sequence 110 | - Catalan numbers 111 | - Burnside's lemma/circular permutation 112 | - Modular inverse 113 | - Probability 114 | - Chinese Remainder Theorem 115 | - Gaussian Elmination method 116 | - Dilworth's Theorem 117 | - Matrix Exponentiation 118 | 119 | 120 | - Computational Geometry 121 | - Pick's Theorem 122 | - Convex hull 123 | - Line Intersection 124 | - Point in a polygon 125 | - Area of a polygon 126 | - Line Sweeping 127 | - Polygon intersection 128 | - Closest Pair 129 | 130 | 131 | - Game Theory 132 | - Take Away Game 133 | - Nim's Game 134 | - Sprague-grundy Number 135 | 136 | - Others 137 | - BackTracking 138 | - N-Queen's Problem 139 | 140 | --- 141 | 142 | ## Introduction 143 | 144 | The type system in C is static and weakly typed. There are built-in types for integers of various sizes, both signed and unsigned, floating-point numbers, and enumerated types (enum). Integer type char is often used for single-byte characters. C99 added a boolean datatype (C99 added a builtin **_Bool** data type , and if you *#include *, it provides **bool** as a macro to **_Bool**.). There are also derived types including arrays, pointers, records (struct), and untagged unions (union). 145 | 146 | ### Primitive types and built-in data structures in C 147 | C is a statically typed language. Each of the variables should be type casted. 148 | There are five basic data types associated with variables: 149 | - **int** - integer: a whole number. 150 | - **float** - floating point value: i.e. a number with a fractional part. 151 | - **double** - a double-precision floating point value. 152 | - **char** - a single character. 153 | - **void** - valueless special purpose type. 154 | 155 | Other than these there are some derived data types. they are - 156 | - **Arrays** 157 | - **Pointers** 158 | - **Structures** 159 | - **Enumeration** 160 | 161 | ##### More details about data types in C: 162 | - [C data types - Tutorialspoint](https://www.tutorialspoint.com/cprogramming/c_data_types.htm) 163 | - [C programming data types - programiz](http://www.programiz.com/c-programming/c-data-types) 164 | 165 | ### Big-O Notation and Time Complexity Analysis 166 | 167 | [Algorithms in plain English: time complexity and Big-O notation](https://medium.freecodecamp.com/time-is-complex-but-priceless-f0abd015063c) 168 | 169 | [Big-O Cheat Sheet Link](http://bigocheatsheet.com/) 170 | 171 | ### How to Use 172 | To test or use codes from this repository you can use any popular IDE, online Editor or compile them locally using GCC compiler. 173 | Following links will help on how to compile a C code in linux. 174 | - http://www.akira.ruc.dk/~keld/teaching/CAN_e14/Readings/How%20to%20Compile%20and%20Run%20a%20C%20Program%20on%20Ubuntu%20Linux.pdf 175 | - http://www.cyberciti.biz/faq/howto-compile-and-run-c-cplusplus-code-in-linux/ 176 | 177 | ###### TL;DR 178 | Run following command to compile a C code (You need to have [gcc compiler](https://help.ubuntu.com/community/InstallingCompilers) installed): 179 | 180 | `gcc file_name.c -o file_name` 181 | 182 | you will get an executable named: `file-name` 183 | 184 | run it using: 185 | 186 | `./file_name` 187 | 188 | ### Useful Links: 189 | * [Algorithms, 4th Edition (book by: Robert Sedgewick and Kevin Wayne)](http://algs4.cs.princeton.edu/home/) 190 | * [Khan Academy tutorial on Algorithms](https://www.khanacademy.org/computing/computer-science/algorithms) 191 | * [Topcoder Tutorials](https://www.topcoder.com/community/data-science/data-science-tutorials/) 192 | * [GeeksforGeeks](http://www.geeksforgeeks.org/) 193 | * [hackerearth Tutorial](https://www.hackerearth.com/practice/) 194 | -------------------------------------------------------------------------------- /Sorting/Bubble Sort/README.md: -------------------------------------------------------------------------------- 1 | # Bubble Sort 2 | 3 | **Bubble Sort** is an algorithm which is used to sort **N** elements that are given in a memory for eg: an Array with N number of elements. Bubble Sort compares all the element one by one and sort them based on their values. 4 | 5 | It is called Bubble sort, because *with each iteration the smaller element in the list bubbles up towards the first place*, just like a water bubble rises up to the water surface. 6 | 7 | Sorting takes place by stepping through all the data items one-by-one in pairs and comparing adjacent data items and swapping each pair that is out of order. 8 | ![bubble sort demonstration](bubble-sort.png) 9 | 10 | 11 | --- 12 | **A visualization on the algorithm:** 13 | 14 | Starting from the beginning of the list, compare every adjacent pair, swap their position if they are not in the right order (the latter one is smaller than the former one). After each iteration, one less element (the last one) is needed to be compared until there are no more elements left to be compared. 15 | 16 | ![Bubble sort gif](https://upload.wikimedia.org/wikipedia/commons/c/c8/Bubble-sort-example-300px.gif) 17 | 18 | ####Complexity Analysis 19 | - Worst Case - O(n2) 20 | - Average Case - O(n2) 21 | - Best Case - O(n) 22 | ### More on this topic 23 | - http://en.wikipedia.org/wiki/Bubble_sort 24 | - http://quiz.geeksforgeeks.org/bubble-sort/ 25 | - https://www.topcoder.com/community/data-science/data-science-tutorials/sorting/ 26 | -------------------------------------------------------------------------------- /Sorting/Bubble Sort/bubble-sort.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Algorithm-archive/Learn-Data_Structure-Algorithm-by-C/e9922b7652ca29ecfc17d6fff4af0c2a2e5225c6/Sorting/Bubble Sort/bubble-sort.png -------------------------------------------------------------------------------- /Sorting/Bubble Sort/bubble_sort.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | //Following function will sort the array in Increasing (ascending) order 4 | void bubble_sort(int arr[], int n) 5 | { 6 | int i, j, tmp; 7 | for(i = 0; i < n-1; i++) 8 | { 9 | // Last i elements are already in place, so the inner loops will run until it reaches the last i elements 10 | for(j = 0; j < n-i-1; j++) 11 | { 12 | if(arr[j] > arr[j+1]) //To Sort in decreasing order, change the comparison operator to '<' 13 | { 14 | tmp = arr[j]; 15 | arr[j] = arr[j+1]; 16 | arr[j+1] = tmp; 17 | } 18 | } 19 | } 20 | } 21 | 22 | //Following is a slightly modified bubble sort function, which tracks the list with a flag to check if it is already sorted 23 | void modified_bubble_sort(int arr[], int n) 24 | { 25 | int i, j, tmp; 26 | for(i = 0; i < n-1; i++) 27 | { 28 | int flag = 0; //Taking a flag variable 29 | // Last i elements are already in place, so the inner loops will run until it reaches the last i elements 30 | for(j = 0; j < n-i-1; j++) 31 | { 32 | if(arr[j] > arr[j+1]) //To Sort in decreasing order, change the comparison operator to '<' 33 | { 34 | tmp = arr[j]; 35 | arr[j] = arr[j+1]; 36 | arr[j+1] = tmp; 37 | 38 | flag = 1; //Setting the flag, if swapping occurs 39 | } 40 | } 41 | 42 | if(!flag) //If not swapped, that means the list has already sorted 43 | { 44 | break; 45 | } 46 | } 47 | } 48 | 49 | void print_list(int arr[], int num_of_element) 50 | { 51 | int i; 52 | for(i = 0; i < num_of_element; i++) 53 | { 54 | printf("%d ", arr[i]); 55 | } 56 | 57 | printf("\n"); 58 | } 59 | 60 | int main(int argc, char const *argv[]) 61 | { 62 | int arr[] = {43, 1, 24, 56, 30, 5}; 63 | int num_of_element = sizeof(arr)/sizeof(int); 64 | 65 | printf("Initial List:\n"); 66 | print_list(arr, num_of_element); 67 | 68 | bubble_sort(arr, num_of_element); 69 | //modified_bubble_sort(arr, num_of_element); 70 | 71 | printf("Sorted list in ascending order: \n"); 72 | print_list(arr, num_of_element); 73 | 74 | return 0; 75 | } 76 | -------------------------------------------------------------------------------- /Sorting/Insertion Sort/README.md: -------------------------------------------------------------------------------- 1 | # Insertion Sort 2 | 3 | **Insertion sort** does exactly what you would expect: it inserts each element of the array into its proper position, leaving progressively larger stretches of the array sorted. What this means in practice is that the sort iterates down an array, and the part of the array already covered is in order; then, the current element of the array is inserted into the proper position at the head of the array, and the rest of the elements are moved down, using the space just vacated by the element inserted as the final space. 4 | 5 | ![Insertion Sort](insertion_sort.jpg) 6 | 7 | 8 | #####A visualization on Insertion Sort 9 | ![Insertion sort demonstration](https://upload.wikimedia.org/wikipedia/commons/0/0f/Insertion-sort-example-300px.gif) 10 | 11 | 12 | ####Complexity Analysis 13 | - Worst Case - О(n2) comparisons, swaps 14 | - Average Case - О(n2) comparisons, swaps 15 | - Best Case - O(n) comparisons, O(1) swaps 16 | ### More on this topic 17 | - https://en.wikipedia.org/wiki/Insertion_sort 18 | - http://quiz.geeksforgeeks.org/insertion-sort/ 19 | - https://www.topcoder.com/community/data-science/data-science-tutorials/sorting/ 20 | -------------------------------------------------------------------------------- /Sorting/Insertion Sort/insertion_sort.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | //Following function will sort the array in Increasing (ascending) order 4 | void insertion_sort(int arr[], int n) 5 | { 6 | int i, current_value, j; 7 | for (i = 1; i < n; i++) 8 | { 9 | current_value = arr[i]; 10 | j = i-1; 11 | 12 | /* Move elements of arr[0..i-1], that are 13 | greater than current_value, to one position ahead 14 | of their current position */ 15 | while (j >= 0 && arr[j] > current_value) 16 | { 17 | arr[j+1] = arr[j]; 18 | j = j-1; 19 | } 20 | arr[j+1] = current_value; 21 | } 22 | } 23 | 24 | void print_list(int arr[], int num_of_element) 25 | { 26 | int i; 27 | for(i = 0; i < num_of_element; i++) 28 | { 29 | printf("%d ", arr[i]); 30 | } 31 | 32 | printf("\n"); 33 | } 34 | 35 | int main(int argc, char const *argv[]) 36 | { 37 | int arr[] = {43, 1, 24, 56, 30, 5}; 38 | int num_of_element = sizeof(arr)/sizeof(int); 39 | 40 | printf("Initial List:\n"); 41 | print_list(arr, num_of_element); 42 | 43 | insertion_sort(arr, num_of_element); 44 | 45 | printf("Sorted list in ascending order: \n"); 46 | print_list(arr, num_of_element); 47 | 48 | return 0; 49 | } 50 | -------------------------------------------------------------------------------- /Sorting/Insertion Sort/insertion_sort.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Algorithm-archive/Learn-Data_Structure-Algorithm-by-C/e9922b7652ca29ecfc17d6fff4af0c2a2e5225c6/Sorting/Insertion Sort/insertion_sort.jpg -------------------------------------------------------------------------------- /Sorting/README.md: -------------------------------------------------------------------------------- 1 | #Sorting 2 | 3 | >A sorting algorithm is an algorithm that puts elements of a list in a certain order. The most-used orders are numerical order and lexicographical order. Efficient sorting is important for optimizing the use of other algorithms (such as search and merge algorithms) which require input data to be in sorted lists; it is also often useful for canonicalizing data and for producing human-readable output. [wikipedia](https://en.wikipedia.org/wiki/Sorting_algorithm) 4 | 5 | 6 | 7 | ###Useful Links: 8 | - [Nice animated visualization of sorting algorithms](https://www.cs.usfca.edu/~galles/visualization/ComparisonSort.html) 9 | - [Sorting visualization](https://visualgo.net/sorting) 10 | - [betterexplained.com article on Sorting algorithms](https://betterexplained.com/articles/sorting-algorithms/) 11 | - [Topcoder article](https://www.topcoder.com/community/data-science/data-science-tutorials/sorting/) 12 | - [Comparison of Sorting algorithms](https://en.wikipedia.org/wiki/Sorting_algorithm#Comparison_of_algorithms) 13 | -------------------------------------------------------------------------------- /Sorting/Selection Sort/README.md: -------------------------------------------------------------------------------- 1 | # Selection Sort 2 | 3 | **Selection sort** is one of the simplest sorting algorithm. 4 | It works by selecting the smallest (or largest, if you want to sort from big to small) element of the array and placing it at the head of the array. Then the process is repeated for the remainder of the array; the next largest element is selected and put into the next slot, and so on down the line. 5 | 6 | ![Selection Sort](selection_sort.jpg) 7 | 8 | Selection sort algorithm starts by compairing first two elements of an array and swapping if necessary, i.e., if you want to sort the elements of array in ascending order and if the first element is greater than second then, you need to swap the elements but, if the first element is smaller than second, leave the elements as it is. Then, again first element and third element are compared and swapped if necessary. This process goes on until first and last element of an array is compared. This completes the first step of selection sort. 9 | 10 | If there are n elements to be sorted then, the process mentioned above should be repeated n-1 times to get required result. 11 | 12 | #####A visualization on Selection Sort 13 | ![Selection sort demonstration](https://upload.wikimedia.org/wikipedia/commons/9/94/Selection-Sort-Animation.gif) 14 | 15 | *Selection sort animation. Red is current min. Yellow is sorted list. Blue is current item.* 16 | 17 | ####Complexity Analysis 18 | - Worst Case - O(n2) 19 | - Average Case - O(n2) 20 | - Best Case - O(n2) 21 | 22 | ### More on this topic 23 | - https://en.wikipedia.org/wiki/Selection_sort 24 | - http://quiz.geeksforgeeks.org/selection-sort/ 25 | - https://www.topcoder.com/community/data-science/data-science-tutorials/sorting/ 26 | -------------------------------------------------------------------------------- /Sorting/Selection Sort/selection_sort.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | //Following function will sort the array in Increasing (ascending) order 4 | void selection_sort(int arr[], int n) 5 | { 6 | int i, j, tmp; 7 | 8 | /* advance the position through the entire array */ 9 | /* (could do i < n-1 because single element is also min element) */ 10 | for (i = 0; i < n-1; i++) 11 | { 12 | // find the min element in the unsorted a[i .. n-1] 13 | 14 | int current_Min = i; // assume the min is the first element 15 | // test against elements after i to find the smallest 16 | for ( j = i+1; j < n; j++) 17 | { 18 | // if this element is less, then it is the new minimum 19 | if (arr[j] < arr[current_Min]) //To sort in decreasing order just change the comparison operator to '>' 20 | { 21 | current_Min = j; // found new minimum; remember its index 22 | } 23 | } 24 | 25 | if(current_Min != i) //if the current_Min is equal to i, then it is in right position already 26 | { 27 | //Swap the values 28 | tmp = arr[i]; 29 | arr[i] = arr[current_Min]; 30 | arr[current_Min] = tmp; 31 | } 32 | } 33 | } 34 | 35 | void print_list(int arr[], int num_of_element) 36 | { 37 | int i; 38 | for(i = 0; i < num_of_element; i++) 39 | { 40 | printf("%d ", arr[i]); 41 | } 42 | 43 | printf("\n"); 44 | } 45 | 46 | int main(int argc, char const *argv[]) 47 | { 48 | int arr[] = {43, 1, 24, 56, 30, 5}; 49 | int num_of_element = sizeof(arr)/sizeof(int); 50 | 51 | printf("Initial List:\n"); 52 | print_list(arr, num_of_element); 53 | 54 | selection_sort(arr, num_of_element); 55 | 56 | printf("Sorted list in ascending order: \n"); 57 | print_list(arr, num_of_element); 58 | 59 | return 0; 60 | } 61 | -------------------------------------------------------------------------------- /Sorting/Selection Sort/selection_sort.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Algorithm-archive/Learn-Data_Structure-Algorithm-by-C/e9922b7652ca29ecfc17d6fff4af0c2a2e5225c6/Sorting/Selection Sort/selection_sort.jpg -------------------------------------------------------------------------------- /Sorting/sorting_algorithms.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Algorithm-archive/Learn-Data_Structure-Algorithm-by-C/e9922b7652ca29ecfc17d6fff4af0c2a2e5225c6/Sorting/sorting_algorithms.png --------------------------------------------------------------------------------