From f298c7655e42920c40a0e7809a7fcb8e09b4c476 Mon Sep 17 00:00:00 2001 From: Paawan Mukker Date: Thu, 4 Oct 2018 02:05:48 +0530 Subject: [PATCH 01/11] README.md: Remove codacy badge, Add travis badge This removes Codacy badge and adds Travis badge to README.md file. Closes https://github.com/NITSkmOS/Algorithms/issues/209 --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index bedd8b06..1c0d18cc 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ [![Gitter](https://badges.gitter.im/NITSkmOS/algo.svg)](https://gitter.im/NITSkmOS/algo?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) [![NITSkmOS Algorithms](https://img.shields.io/badge/NITSkmOS-Algorithms-blue.svg)](https://github.com/NITSkmOS/Algorithms) -[![Codacy Badge](https://api.codacy.com/project/badge/Grade/29024673e94b48459809432cdd280e39)](https://app.codacy.com/app/NITSkmOS/Algorithms?utm_source=github.com&utm_medium=referral&utm_content=NITSkmOS/Algorithms&utm_campaign=Badge_Grade_Settings) +[![Build Status](https://travis-ci.com/NITSkmOS/Algorithms.svg?branch=master)](https://travis-ci.com/NITSkmOS/Algorithms) [![GitHub](https://img.shields.io/github/license/mashape/apistatus.svg)](https://github.com/NITSkmOS/Algorithms/blob/master/LICENSE) From e72f3e1b209d5f0cb0854398bfb806d94891ae30 Mon Sep 17 00:00:00 2001 From: halderjoydeep Date: Thu, 4 Oct 2018 12:47:16 +0530 Subject: [PATCH 02/11] max_sub_array.py: Add Maximum Subarray Divide and Conquer method to solve maximum subarray problem closes https://github.com/NITSkmOS/Algorithms/issues/215 --- README.md | 1 + maximum_subarray/Python/max_sub_array.py | 102 +++++++++++++++++++++++ 2 files changed, 103 insertions(+) create mode 100644 maximum_subarray/Python/max_sub_array.py diff --git a/README.md b/README.md index 1c0d18cc..6a05f063 100644 --- a/README.md +++ b/README.md @@ -22,6 +22,7 @@ This repository contains examples of various algorithms written on different pro | [Bubble Sort](https://en.wikipedia.org/wiki/Bubble_sort) | [:octocat:](bubble_sort/C) | [:octocat:](bubble_sort/Cpp) | | | | [Shell Sort](https://en.wikipedia.org/wiki/Shellsort) | [:octocat:](shell_sort/C) | | | [:octocat:](shell_sort/Python) | | [Heap Sort](https://en.wikipedia.org/wiki/Heapsort) | | | | [:octocat:](heap_sort/python) | +| [Maximum Subarray Problem](https://en.wikipedia.org/wiki/Maximum_subarray_problem) | | | | [:octocat:](/maximum_subarray/Python)| ## Implemented Data Structures diff --git a/maximum_subarray/Python/max_sub_array.py b/maximum_subarray/Python/max_sub_array.py new file mode 100644 index 00000000..f6961530 --- /dev/null +++ b/maximum_subarray/Python/max_sub_array.py @@ -0,0 +1,102 @@ +""" +Here Maximum SubArray problem has been implemented on the Share +Market Data Analysis. Where prices of every day has been given. +We have to find the buying and selling day so that the profit will +be maximum. Here the Divide and Conquer method is used and +time-complexity is O(nlogn).For more information visit- + +""" + + +def max_sub_array(arr, low, high): + """ + Method to find maximum sub array. + + :param low: kjndn + :param high: kjndknfg + """ + if low == high: + # if there is only one day + return low, low + 1, arr[low] + + else: + mid = int((low + high) / 2) + # ll, lh, ls are respectively left-low, left-high, left-sum + # rl, rh, rs are respectively right-low, right-high, right-sum + # cl, ch, cs are respectively cross-low, cross-high, cross-sum + + ll, lh, ls = max_sub_array(arr, low, mid) + rl, rh, rs = max_sub_array(arr, mid + 1, high) + cl, ch, cs = cross_sub_array(arr, low, mid, high) + + max_sum = max(ls, rs, cs) + + if max_sum is ls: + return ll, lh, ls + elif max_sum is rs: + return rl, rh, rs + else: + return cl, ch, cs + + +def cross_sub_array(arr, low, mid, high): + """ + :param mid: lsum is left sum + """ + lsum = -10000 + sum = 0 + maxl = mid + maxr = mid + 1 + for i in range(mid, low - 1, -1): + sum = sum + arr[i] + if sum > lsum: + lsum = sum + maxl = i + + # rsum is right sum + rsum = -10000 + sum = 0 + for i in range(mid + 1, high + 1): + sum = sum + arr[i] + if sum > rsum: + rsum = sum + maxr = i + 1 + return maxl, maxr, (lsum + rsum) + + +def main(): + # price is array of the prices where each index of array + # represents the day. + # price_difference is array of profit(either +ve or -ve) + + price = [4, 9, 5, 13, 16, 7, 8] + + if len(price) <= 1: + print('Same day purchase and sell.So no profit.') + return + + price_difference = [] + for day in range(1, len(price)): + price_difference.append(price[day] - price[day - 1]) + + # l is day of purchasing + # h is day of selling + # s is profit + + l, h, s = max_sub_array(price_difference, 0, (len(price_difference) - 1)) + if s < 0: + # if it happens that price drops and never rises to + # the price when it was purchased + + print('No days found to get profit') + else: + # To be more real-life oriented we start counting from day-1 instead of + # day-0 + + print('Day of Purchase:', l + 1, + '\nDay of Selling:', h + 1, + '\nProfit:', s) + + +if __name__ == '__main__': + main() From ecdd0d3d6b61a5cc1673220a88825259dc251a1e Mon Sep 17 00:00:00 2001 From: halderjoydeep Date: Sun, 7 Oct 2018 23:25:15 +0530 Subject: [PATCH 03/11] knapsack.py : Add KnapSack Problem Greedy approach to solve the knapsack problem closes https://github.com/NITSkmOS/Algorithms/issues/305 --- README.md | 1 + knapsack_problem/Python/knapsack.py | 60 +++++++++++++++++++++++++++++ 2 files changed, 61 insertions(+) create mode 100644 knapsack_problem/Python/knapsack.py diff --git a/README.md b/README.md index 6a05f063..a9b8f78a 100644 --- a/README.md +++ b/README.md @@ -23,6 +23,7 @@ This repository contains examples of various algorithms written on different pro | [Shell Sort](https://en.wikipedia.org/wiki/Shellsort) | [:octocat:](shell_sort/C) | | | [:octocat:](shell_sort/Python) | | [Heap Sort](https://en.wikipedia.org/wiki/Heapsort) | | | | [:octocat:](heap_sort/python) | | [Maximum Subarray Problem](https://en.wikipedia.org/wiki/Maximum_subarray_problem) | | | | [:octocat:](/maximum_subarray/Python)| +| [Knapsack Problem](https://en.wikipedia.org/wiki/Knapsack_problem) | | | | [:octocat:](knapsack_problem/Python)| ## Implemented Data Structures diff --git a/knapsack_problem/Python/knapsack.py b/knapsack_problem/Python/knapsack.py new file mode 100644 index 00000000..0ca11ccb --- /dev/null +++ b/knapsack_problem/Python/knapsack.py @@ -0,0 +1,60 @@ +def knapsack(profit, weight, capacity): + """ + Here Knapsack problem has been implemented using Greedy Approach + where the weight and and corresponding profit of some items has been + given. And also the maximum capacity of a sack(bag) is given. we have + to take items so that capacity does not exceed and we get maximum profit. + For more information visit: + + :param profit: array of profit of the items + :param weight: array of weight of the items + :param capacity: capacity of the sack + :return: maximum profit and the fraction of items + """ + + # array of profit/weight ratio + ratio = [v / w for v, w in zip(profit, weight)] + + # a list of (0, 1, ..., n-1) + index = list(range(len(profit))) + + # index is sorted according to ratio in descending order + index.sort(key=lambda i: ratio[i], reverse=True) + + # max_profit is the maximum profit gained + max_profit = 0 + + # fraction is the fraction in which items should be taken + fraction = [0] * len(profit) + + for i in index: + if weight[i] <= capacity: + fraction[i] = 1 + max_profit += profit[i] + capacity -= weight[i] + else: + fraction[i] = capacity / weight[i] + max_profit += profit[i] * fraction[i] + break + + return max_profit, fraction + + +def main(): + # profit is array of profit of the items + # weight is array of weight of the items + # capacity is capacity of the sack + + profit = [50, 60, 80] + weight = [10, 30, 20] + capacity = 50 + + # max_profit is the maximum profit gained + # fraction is the fraction in which items should be taken + max_profit, fraction = knapsack(profit, weight, capacity) + print('Maximum profit:', max_profit) + print('Items should be taken in fraction of:', fraction) + + +if __name__ == '__main__': + main() From 5dc719523305522973509a4e877b19eef3ccf31e Mon Sep 17 00:00:00 2001 From: Paawan Mukker Date: Mon, 8 Oct 2018 00:16:07 +0530 Subject: [PATCH 04/11] counting_sort.cpp: Add Counting Sort Algorithm This adds Counting sort which sorts array by counting the occurences of elements. Closes https://github.com/NITSkmOS/Algorithms/issues/299 --- README.md | 2 +- counting_sort/Cpp/counting_sort.cpp | 73 +++++++++++++++++++++++++++++ 2 files changed, 74 insertions(+), 1 deletion(-) create mode 100644 counting_sort/Cpp/counting_sort.cpp diff --git a/README.md b/README.md index a9b8f78a..f2143b4c 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ This repository contains examples of various algorithms written on different pro | [QuickSort](https://en.wikipedia.org/wiki/Quicksort) | | | | [:octocat:](quicksort/Python) | | [Merge Sort](https://en.wikipedia.org/wiki/Merge_sort) | | | | [:octocat:](merge_sort/Python) | | [Insertion Sort](https://en.wikipedia.org/wiki/Insertion_sort) | [:octocat:](insertion_sort/C) | [:octocat:](insertion_sort/Cpp) | | [:octocat:](insertion_sort/Python) | -| [Counting Sort](https://en.wikipedia.org/wiki/Counting_sort) | | | | [:octocat:](counting_sort/Python) | +| [Counting Sort](https://en.wikipedia.org/wiki/Counting_sort) | | [:octocat:](counting_sort/Cpp) | | [:octocat:](counting_sort/Python) | | [Radix Sort](https://en.wikipedia.org/wiki/Radix_sort) | | | | [:octocat:](radix_sort/Python) | | [Binary Search](https://en.wikipedia.org/wiki/Binary_search_algorithm) | | [:octocat:](binary_search/Cpp) | | [:octocat:](binary_search/Python) | | [Bubble Sort](https://en.wikipedia.org/wiki/Bubble_sort) | [:octocat:](bubble_sort/C) | [:octocat:](bubble_sort/Cpp) | | | diff --git a/counting_sort/Cpp/counting_sort.cpp b/counting_sort/Cpp/counting_sort.cpp new file mode 100644 index 00000000..f1677551 --- /dev/null +++ b/counting_sort/Cpp/counting_sort.cpp @@ -0,0 +1,73 @@ +#include +#include +#include +using namespace std; + +/* +Counting sort implementation for sorting given array. +Note - Works on Non-negative integer array only. + +Parameters: +int a[] - Integer array a to be sorted. +int n - size of array a. +int r. - Range of numbers in a. +*/ + +void counting_sort(int a[], int n, int r) { + if(a == NULL) return; + + int *cnt = new int[r+1]; //array to store count of each occurences + int *out = new int[n]; //Out array to store sorted values + + + // Intitialise the count array to 0 + for (int i = 0; i <= r; ++i) + cnt[i] = 0; + + // Count each occurences digit wise + for (int i = 0; i < n; ++i) + cnt[a[i]]++; + + // Cumulative count array + for (int i = 1; i <= r; ++i) + cnt[i]+=cnt[i-1]; + + // Sort + for (int i = n - 1; i >= 0; i--) { + // Note - starting from n-1 to maintain "stable sort" property + out[cnt[a[i]] - 1] = a[i]; + cnt[a[i]]--; + } + + // Copy results back to orignal array + for (int i = 0; i < n; i++) + a[i] = out[i]; +} + + +int main() { + ios_base::sync_with_stdio(false); //For faster io + int a[] = {1, 2, 9, 293, 41, 15, 52, 3, 121, 7, 1223, 3449, 15, 1 }; + int n = sizeof(a)/sizeof(a[0]); + + // Get the iterator to max element for calculating range of number + int * max_a_itr = max_element(a, a+n); + int max_a = *max_a_itr; + + + cout << "Input Array:\n"; + for (int i = 0; i < n; i++) { + cout << a[i] << " "; + } + cout << "\n"; + + counting_sort(a, n, max_a); + + cout << "Sorted Array:\n"; + for (int i = 0; i < n; i++) { + cout << a[i] << " "; + } + cout << "\n"; + + return 0; +} From 013c77d7285a1178d660468dd03d020590956d14 Mon Sep 17 00:00:00 2001 From: Paawan Mukker Date: Sat, 6 Oct 2018 00:53:17 +0530 Subject: [PATCH 05/11] radix_sort.cpp: Add Radix Sort Algorithm This adds Radix sort. It sorts array digit by digit. Closes https://github.com/NITSkmOS/Algorithms/issues/222 --- README.md | 2 +- radix_sort/Cpp/radix_sort.cpp | 97 +++++++++++++++++++++++++++++++++++ 2 files changed, 98 insertions(+), 1 deletion(-) create mode 100644 radix_sort/Cpp/radix_sort.cpp diff --git a/README.md b/README.md index f2143b4c..8524caf7 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,7 @@ This repository contains examples of various algorithms written on different pro | [Merge Sort](https://en.wikipedia.org/wiki/Merge_sort) | | | | [:octocat:](merge_sort/Python) | | [Insertion Sort](https://en.wikipedia.org/wiki/Insertion_sort) | [:octocat:](insertion_sort/C) | [:octocat:](insertion_sort/Cpp) | | [:octocat:](insertion_sort/Python) | | [Counting Sort](https://en.wikipedia.org/wiki/Counting_sort) | | [:octocat:](counting_sort/Cpp) | | [:octocat:](counting_sort/Python) | -| [Radix Sort](https://en.wikipedia.org/wiki/Radix_sort) | | | | [:octocat:](radix_sort/Python) | +| [Radix Sort](https://en.wikipedia.org/wiki/Radix_sort) | | [:octocat:](radix_sort/Cpp) | | [:octocat:](radix_sort/Python) | | [Binary Search](https://en.wikipedia.org/wiki/Binary_search_algorithm) | | [:octocat:](binary_search/Cpp) | | [:octocat:](binary_search/Python) | | [Bubble Sort](https://en.wikipedia.org/wiki/Bubble_sort) | [:octocat:](bubble_sort/C) | [:octocat:](bubble_sort/Cpp) | | | | [Shell Sort](https://en.wikipedia.org/wiki/Shellsort) | [:octocat:](shell_sort/C) | | | [:octocat:](shell_sort/Python) | diff --git a/radix_sort/Cpp/radix_sort.cpp b/radix_sort/Cpp/radix_sort.cpp new file mode 100644 index 00000000..61e44f0d --- /dev/null +++ b/radix_sort/Cpp/radix_sort.cpp @@ -0,0 +1,97 @@ +#include +#include +#include +using namespace std; + +/* +Utility function for Radix sort to sort given array for dth digit. +This is essentially modified version of counting sort. + +Parameters: +int a[] - Integer array a to be sorted. +int n - size of array a. +int d - Digit by which to sort the array with (0 based indexing). +*/ + +void radix_digit_util(int a[], int n, int d) { + if(a == NULL) return; + + int exp = pow(10, d); + + int *cnt = new int[10]; //array to store count of each occurences + int *out = new int[n]; //Out array to store sorted values + + // Intitialise the count array to 0 + for (int i = 0; i < n; ++i) + cnt[i] = 0; + + // Count each occurences digit wise + for (int i = 0; i < n; ++i) + cnt[(a[i]/exp)%10]++; + + // Cumulative count array + for (int i = 1; i < n; ++i) + cnt[i]+=cnt[i-1]; + + // Sort + for (int i = n - 1; i >= 0; i--) { + // Note - starting from n-1 to maintain "stable sort" property + out[cnt[(a[i]/exp)%10] - 1] = a[i]; + cnt[(a[i]/exp)%10]--; + } + + // Copy results back to orignal array + for (int i = 0; i < n; i++) + a[i] = out[i]; +} + + +/* +Radix sort implementation for sorting given array assuming the base 10. +Note - // Works on Non-negative integer array only. + +Parameters: +int a[] - Non-negative Integer array a to be sorted. +int n - size of array a. +*/ +void radix_sort(int a[], int n) { + if(a == NULL) return; + + // Get the iterator to max element for calculating maximum number of digits. + int * max_a_itr = max_element(a, a+n); + int max_a = *max_a_itr; + + // Get maximum number of digits of all elements in array a + int max_d = 0; + while(max_a) { + max_d++; + max_a = max_a/10; + } + + // Sort the array digit wise starting from lowest significant digit to highest. + for (int d = 0; d < max_d; d++) + radix_digit_util(a, n, d); +} + + +int main() { + ios_base::sync_with_stdio(false); //For faster io + int a[] = {1, 2, 9, 293, 41, 15, 52, 3, 121, 7, 1223, 3449, 15, 1 }; + int n = sizeof(a)/sizeof(a[0]); + + cout << "Input Array:\n"; + for (int i = 0; i < n; i++) { + cout << a[i] << " "; + } + cout << "\n"; + + radix_sort(a, n); + + cout << "Sorted Array:\n"; + for (int i = 0; i < n; i++) { + cout << a[i] << " "; + } + cout << "\n"; + + return 0; +} From 8d4d599c75fa7ee8cd79c1125997655318152ac3 Mon Sep 17 00:00:00 2001 From: Vivek R <123vivekr@gmail.com> Date: Thu, 11 Oct 2018 15:26:12 +0530 Subject: [PATCH 06/11] merge_sort.c: Add Merge Sort in C This adds Merge Sort algorithm written in C Closes https://github.com/NITSkmOS/Algorithms/issues/147 --- README.md | 2 +- merge_sort/C/merge_sort.c | 73 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 74 insertions(+), 1 deletion(-) create mode 100644 merge_sort/C/merge_sort.c diff --git a/README.md b/README.md index 8524caf7..3e5e2f47 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,7 @@ This repository contains examples of various algorithms written on different pro |:----------------------------------------------------------------------------------------------- |:-------------------------------------:|:-------------------------------------:|:-------------------------------------:|:-------------------------------------:| | [Euclidean GCD](https://en.wikipedia.org/wiki/Euclidean_algorithm) | [:octocat:](euclidean_gcd/C) | | [:octocat:](euclidean_gcd/Java) | [:octocat:](euclidean_gcd/Python) | | [QuickSort](https://en.wikipedia.org/wiki/Quicksort) | | | | [:octocat:](quicksort/Python) | -| [Merge Sort](https://en.wikipedia.org/wiki/Merge_sort) | | | | [:octocat:](merge_sort/Python) | +| [Merge Sort](https://en.wikipedia.org/wiki/Merge_sort) | [:octocat:](merge_sort/C) | | | [:octocat:](merge_sort/Python) | | [Insertion Sort](https://en.wikipedia.org/wiki/Insertion_sort) | [:octocat:](insertion_sort/C) | [:octocat:](insertion_sort/Cpp) | | [:octocat:](insertion_sort/Python) | | [Counting Sort](https://en.wikipedia.org/wiki/Counting_sort) | | [:octocat:](counting_sort/Cpp) | | [:octocat:](counting_sort/Python) | | [Radix Sort](https://en.wikipedia.org/wiki/Radix_sort) | | [:octocat:](radix_sort/Cpp) | | [:octocat:](radix_sort/Python) | diff --git a/merge_sort/C/merge_sort.c b/merge_sort/C/merge_sort.c new file mode 100644 index 00000000..0bc10c4f --- /dev/null +++ b/merge_sort/C/merge_sort.c @@ -0,0 +1,73 @@ +#include // for printf function + +// Function prototypes +void mergesort(int[], int, int); +void merge(int[], int, int, int); + +int main() { + int arr_size = 6; + int arr[6] = {10, 9, 8, 7, 6, 5}; + mergesort(arr, 0, arr_size); + + // Print sorted array + for (int i = 0; i < arr_size; i++) { + printf("%d ", arr[i]); + } + printf("\n"); + + return 0; +} + +/* + * Recursively split the array and call the merge function + * Main entry point of Merge Sort + */ +void mergesort(int arr[], int l, int r) { + if(l >= r) + return; + int m = (l + r) / 2; + mergesort(arr, l, m); + mergesort(arr, m+1, r); + merge(arr, l, m, r); +} + +// Merges the arrays in ascending order of elements +void merge(int arr[], int l, int m, int r) { + int i, j, k; + int n1 = m - l + 1; + int n2 = r - m; + + int L[n1], M[n2]; + + for(i = 0; i < n1; ++i) + L[i] = arr[l+i]; + for(j = 0; j < n2; ++j) + M[j] = arr[m + 1 + j]; + + i = 0; + j = 0; + k = l; + + while(i < n1 && j < n2) { + if(L[i] <= M[j]) { + arr[k] = L[i]; + ++i; + } else { + arr[k] = M[j]; + ++j; + } + ++k; + } + + while(i < n1) { + arr[k] = L[i]; + ++i; + ++k; + } + + while(j < n2) { + arr[k] = M[j]; + ++j; + ++k; + } +} From b19bd47a40f30dd7a5a72a1f4fa6236cfe34a33d Mon Sep 17 00:00:00 2001 From: Paawan Mukker Date: Wed, 10 Oct 2018 00:13:01 +0530 Subject: [PATCH 07/11] counting_sort.c: Add Counting Sort Algorithm This adds Counting sort implementation in C. Closes https://github.com/NITSkmOS/Algorithms/issues/381 --- README.md | 2 +- counting_sort/C/counting_sort.c | 73 +++++++++++++++++++++++++++++++++ 2 files changed, 74 insertions(+), 1 deletion(-) create mode 100644 counting_sort/C/counting_sort.c diff --git a/README.md b/README.md index 3e5e2f47..3d31ddcc 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ This repository contains examples of various algorithms written on different pro | [QuickSort](https://en.wikipedia.org/wiki/Quicksort) | | | | [:octocat:](quicksort/Python) | | [Merge Sort](https://en.wikipedia.org/wiki/Merge_sort) | [:octocat:](merge_sort/C) | | | [:octocat:](merge_sort/Python) | | [Insertion Sort](https://en.wikipedia.org/wiki/Insertion_sort) | [:octocat:](insertion_sort/C) | [:octocat:](insertion_sort/Cpp) | | [:octocat:](insertion_sort/Python) | -| [Counting Sort](https://en.wikipedia.org/wiki/Counting_sort) | | [:octocat:](counting_sort/Cpp) | | [:octocat:](counting_sort/Python) | +| [Counting Sort](https://en.wikipedia.org/wiki/Counting_sort) |[:octocat:](counting_sort/C) | [:octocat:](counting_sort/Cpp) | | [:octocat:](counting_sort/Python) | | [Radix Sort](https://en.wikipedia.org/wiki/Radix_sort) | | [:octocat:](radix_sort/Cpp) | | [:octocat:](radix_sort/Python) | | [Binary Search](https://en.wikipedia.org/wiki/Binary_search_algorithm) | | [:octocat:](binary_search/Cpp) | | [:octocat:](binary_search/Python) | | [Bubble Sort](https://en.wikipedia.org/wiki/Bubble_sort) | [:octocat:](bubble_sort/C) | [:octocat:](bubble_sort/Cpp) | | | diff --git a/counting_sort/C/counting_sort.c b/counting_sort/C/counting_sort.c new file mode 100644 index 00000000..db9ee993 --- /dev/null +++ b/counting_sort/C/counting_sort.c @@ -0,0 +1,73 @@ +#include +#include + +/* +Counting sort implementation for sorting given array. +Note - Works on Non-negative integer array only. + +Parameters: +int a[] - Integer array a to be sorted. +int n - size of array a. +int r. - Range of numbers in a. +*/ + +void counting_sort(int a[], int n, int r) { + if(a == NULL) return; + + //array to store count of each occurences + int *cnt = (int *) malloc((r+1)*sizeof(int)); // Ignore CPPLintBear + //Out array to store sorted values + int *out = (int *) malloc((n)*sizeof(int)); // Ignore CPPLintBear + + + // Intitialise the count array to 0 + for (int i = 0; i <= r; ++i) + cnt[i] = 0; + + // Count each occurences digit wise + for (int i = 0; i < n; ++i) + cnt[a[i]]++; + + // Cumulative count array + for (int i = 1; i <= r; ++i) + cnt[i]+=cnt[i-1]; + + // Sort + for (int i = n - 1; i >= 0; i--) { + // Note - starting from n-1 to maintain "stable sort" property + out[cnt[a[i]] - 1] = a[i]; + cnt[a[i]]--; + } + + // Copy results back to orignal array + for (int i = 0; i < n; i++) + a[i] = out[i]; +} + + +int main() { + int a[] = {1, 2, 9, 293, 41, 15, 52, 3, 121, 7, 1223, 3449, 15, 1 }; + int n = sizeof(a)/sizeof(a[0]); + + // Get the max element for calculating range of number + int max_a = a[0]; + for (int i = 1; i < n; ++i) + if(max_a < a[i]) max_a = a[i]; + + + printf("Input Array:\n"); + for (int i = 0; i < n; i++) { + printf("%d ", a[i]); + } + printf("\n"); + + counting_sort(a, n, max_a); + + printf("Sorted Array:\n"); + for (int i = 0; i < n; i++) { + printf("%d ", a[i]); + } + printf("\n"); + + return 0; +} From 8974cc774b6cceecc0a40cde89cb402202ced454 Mon Sep 17 00:00:00 2001 From: Vivek R <123vivekr@gmail.com> Date: Wed, 3 Oct 2018 00:02:47 +0530 Subject: [PATCH 08/11] quick_sort.c: Add Quick Sort in C This adds Quick Sort algorithm written in C Closes https://github.com/NITSkmOS/Algorithms/issues/146 --- README.md | 2 +- quicksort/C/quick_sort.c | 53 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+), 1 deletion(-) create mode 100644 quicksort/C/quick_sort.c diff --git a/README.md b/README.md index 3d31ddcc..7380b2af 100644 --- a/README.md +++ b/README.md @@ -13,8 +13,8 @@ This repository contains examples of various algorithms written on different pro | Algorithm | C | CPP | Java | Python | |:----------------------------------------------------------------------------------------------- |:-------------------------------------:|:-------------------------------------:|:-------------------------------------:|:-------------------------------------:| | [Euclidean GCD](https://en.wikipedia.org/wiki/Euclidean_algorithm) | [:octocat:](euclidean_gcd/C) | | [:octocat:](euclidean_gcd/Java) | [:octocat:](euclidean_gcd/Python) | -| [QuickSort](https://en.wikipedia.org/wiki/Quicksort) | | | | [:octocat:](quicksort/Python) | | [Merge Sort](https://en.wikipedia.org/wiki/Merge_sort) | [:octocat:](merge_sort/C) | | | [:octocat:](merge_sort/Python) | +| [QuickSort](https://en.wikipedia.org/wiki/Quicksort) | [:octocat:](quicksort/C) | | | [:octocat:](quicksort/Python) | | [Insertion Sort](https://en.wikipedia.org/wiki/Insertion_sort) | [:octocat:](insertion_sort/C) | [:octocat:](insertion_sort/Cpp) | | [:octocat:](insertion_sort/Python) | | [Counting Sort](https://en.wikipedia.org/wiki/Counting_sort) |[:octocat:](counting_sort/C) | [:octocat:](counting_sort/Cpp) | | [:octocat:](counting_sort/Python) | | [Radix Sort](https://en.wikipedia.org/wiki/Radix_sort) | | [:octocat:](radix_sort/Cpp) | | [:octocat:](radix_sort/Python) | diff --git a/quicksort/C/quick_sort.c b/quicksort/C/quick_sort.c new file mode 100644 index 00000000..aaa17789 --- /dev/null +++ b/quicksort/C/quick_sort.c @@ -0,0 +1,53 @@ +#include + +void quick_sort(int[], int, int); +void print_array(int[], int); +int partition(int[], int, int); +void swap(int*, int*); + +int main() { + int arr[] = {45, 92, 54, 23, 6, 4, 12}; + int n = sizeof(arr) / sizeof(arr[0]); + quick_sort(arr, 0, n); + printf("Sorted array: \n"); + print_array(arr, n); +} + +void swap(int *a, int *b) { + int temp = *a; + *a = *b; + *b = temp; +} + +/* Quick Sort algorithm */ +void quick_sort(int arr[], int lb, int ub) { + if (lb < ub) { + int pi = partition(arr, lb, ub); + + quick_sort(arr, lb, pi - 1); + quick_sort(arr, pi + 1, ub); + } +} + +/* Partitioning function */ +int partition(int arr[], int low, int high) { + int i = low + 1; + int piv = arr[low]; + + for (int j = low + 1; j <= high; ++j) { + if (arr[j] < piv) { + swap(&arr[i], &arr[j]); + i++; + } + } + swap(&arr[low], &arr[i - 1]); + return i - 1; +} + +/* Function to print array */ +void print_array(int arr[], int size) { + int i; + for (i = 0; i < size; i++) + printf("%d ", arr[i]); + printf("\n"); +} From 67e0d9b7571d271b699fd9d2d64a6768a300ee8a Mon Sep 17 00:00:00 2001 From: Bihan V de Silva Date: Sun, 14 Oct 2018 14:10:13 +0530 Subject: [PATCH 09/11] linked_list.cpp : Add linked list in C++ This adds the singly linked list data structure in C++ langauge. Singly linked list stores the value of a node as well as a pointer to the next node. Utility functions for adding / deleting as well as driver code is included. Closes https://github.com/NITSkmOS/Algorithms/issues/27 --- README.md | 2 +- linked_list/cpp/linked_list.cpp | 188 ++++++++++++++++++++++++++++++++ 2 files changed, 189 insertions(+), 1 deletion(-) create mode 100644 linked_list/cpp/linked_list.cpp diff --git a/README.md b/README.md index 7380b2af..151e1598 100644 --- a/README.md +++ b/README.md @@ -32,7 +32,7 @@ This repository contains examples of various algorithms written on different pro |:----------------------------------------------------------------------------------------------- |:-------------------------------------:|:-------------------------------------:|:-------------------------------------:|:-------------------------------------:| | [Queue](https://en.wikipedia.org/wiki/Queue_(abstract_data_type)) | | [:octocat:](queue/Cpp) | | | | [Stack](https://en.wikipedia.org/wiki/Stack_(abstract_data_type)) | | | [:octocat:](stack/Java) | [:octocat:](stack/Python) | -| [Linear Linked List](https://en.wikipedia.org/wiki/Linked_list) | [:octocat:](linked_list/C) | | | [:octocat:](linked_list/Python) | +| [Linear Linked List](https://en.wikipedia.org/wiki/Linked_list) | [:octocat:](linked_list/C) | [:octocat:](linked_list/Cpp) | | [:octocat:](linked_list/Python) | | [AVL Tree](https://en.wikipedia.org/wiki/AVL_tree) | [:octocat:](avl_tree/C) | | [:octocat:](avl_tree/Java) | [:octocat:](avl_tree/Python) | diff --git a/linked_list/cpp/linked_list.cpp b/linked_list/cpp/linked_list.cpp new file mode 100644 index 00000000..19556247 --- /dev/null +++ b/linked_list/cpp/linked_list.cpp @@ -0,0 +1,188 @@ +#include + +using namespace std; + +/* + * The node structure will hold the data and the address of the next node + */ +struct node { + int data; + node *next; +}; + +/* + * The list class is the implementation of the singly linked list + */ +class list { + private: + node *head, *tail; + + public: + list(); + void createNode(int value); + void displayValues(); + void insertAtStart(int value); + void insertAtPosition(int pos, int value); + void deleteFirstNode(); + void deleteLastNode(); + void deleteAtPosition(int pos); +}; + +/* + * constructor + */ +list::list() { + head = NULL; + tail = NULL; +} + +/* + * This method creates a new node and adds it to the end of the list. + * If the list is empty (head is NULL) then the new node becomes both the head + * and the tail. + */ +void list::createNode(int value) { + node *temp = new node; + temp -> data = value; + temp -> next = NULL; + + if (head == NULL) { + head = temp; + tail = temp; + temp = NULL; + } else { + tail -> next = temp; + tail = temp; + } +} + +/* + * Displays the values in the list, seperated by tabs. + */ +void list::displayValues() { + node *temp = new node; + temp = head; + + while (temp != NULL) { + cout << temp -> data << "\t"; + temp = temp -> next; + } + + cout << "\n"; +} + +/* + * Insert a new node at the start of the list + */ +void list::insertAtStart(int value) { + node *temp = new node; + temp -> data = value; + temp -> next = head; + head = temp; +} + +/* + * Insert a new node at a given position + */ +void list::insertAtPosition(int pos, int value) { + node *previous = new node; + node *current = new node; + node *temp = new node; + current = head; + + for (int i=1; i < pos; i++) { + previous = current; + current = current -> next; + } + + temp -> data = value; + previous -> next = temp; + temp -> next = current; +} + +/* + * Delete the very first node in the list + */ +void list::deleteFirstNode() { + node *temp = new node; + temp = head; + head = head -> next; + delete temp; +} + +/* + * Delete the last node in the list. + */ +void list::deleteLastNode() { + node *current = new node; + node *previous = new node; + current = head; + + while (current -> next != NULL) { + previous = current; + current = current -> next; + } + + tail = previous; + previous -> next = NULL; + delete current; +} + +/* + * Delete a list node at a given position. + */ +void list::deleteAtPosition(int pos) { + node *current = new node; + node *previous = new node; + current = head; + + for (int i=1; i < pos; i++) { + previous = current; + current = current -> next; + } + + previous -> next = current -> next; +} + +/* + * Driver code for testing. + */ +int main() { + // create a new list; + list linked_list; + + // add items using createNode + linked_list.createNode(5); + linked_list.createNode(10); + + // the linked_list now contains 5, 10 + linked_list.displayValues(); + + // insert a value at the beginning of the list + linked_list.insertAtStart(0); + + // the linked_list now contains 0, 5, 10 + // insert another value + linked_list.createNode(20); + + // the linked_list now contains 0, 5, 10, 20 + // insert value at position + linked_list.insertAtPosition(4, 15); + + // the linked_list now contains 0, 5, 10, 15, 20 + // delete the first node + linked_list.deleteFirstNode(); + + // the linked_list now contains 5, 10, 15, 20 + // delete the last node + linked_list.deleteLastNode(); + + // the linked_list now contains 5, 10, 15 + // delete node at position + linked_list.deleteAtPosition(2); + + // the linked_list now contains 5, 15 + linked_list.displayValues(); + + return 0; +} From 347ad07ecb5a415e82e68fa5013e65187b6fbba3 Mon Sep 17 00:00:00 2001 From: Nitish Jadia Date: Sun, 14 Oct 2018 16:02:26 +0530 Subject: [PATCH 10/11] stack.c: Add stack using array in C This adds stack data structure code in C. Closes https://github.com/NITSkmOS/Algorithms/issues/40 --- README.md | 2 +- stack/C/stack.c | 39 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) create mode 100644 stack/C/stack.c diff --git a/README.md b/README.md index 151e1598..ed258d25 100644 --- a/README.md +++ b/README.md @@ -31,7 +31,7 @@ This repository contains examples of various algorithms written on different pro | Data Structure | C | CPP | Java | Python | |:----------------------------------------------------------------------------------------------- |:-------------------------------------:|:-------------------------------------:|:-------------------------------------:|:-------------------------------------:| | [Queue](https://en.wikipedia.org/wiki/Queue_(abstract_data_type)) | | [:octocat:](queue/Cpp) | | | -| [Stack](https://en.wikipedia.org/wiki/Stack_(abstract_data_type)) | | | [:octocat:](stack/Java) | [:octocat:](stack/Python) | +| [Stack](https://en.wikipedia.org/wiki/Stack_(abstract_data_type)) | [:octocat:](stack/C ) | | [:octocat:](stack/Java) | [:octocat:](stack/Python) | | [Linear Linked List](https://en.wikipedia.org/wiki/Linked_list) | [:octocat:](linked_list/C) | [:octocat:](linked_list/Cpp) | | [:octocat:](linked_list/Python) | | [AVL Tree](https://en.wikipedia.org/wiki/AVL_tree) | [:octocat:](avl_tree/C) | | [:octocat:](avl_tree/Java) | [:octocat:](avl_tree/Python) | diff --git a/stack/C/stack.c b/stack/C/stack.c new file mode 100644 index 00000000..ade7034a --- /dev/null +++ b/stack/C/stack.c @@ -0,0 +1,39 @@ +#include +#include + +/*Using variable i to push elements then pop and print the elements. */ + +int main() { + void push(int *arr, int *top, int n, int i); + int pop(int *arr, int *top); + // number of elements + int n = 6; + int arr[n], top = -1; + // push all elements into the stack + for(int i = 0; i < n; i++) { + push(arr, &top, n, i); + } + printf("\n"); + // pop elements one by one. + for(int i = 0; i < n; i++) { + printf("%d ", pop(arr, &top)); + } +} + +void push(int *arr, int *top, int n, int i) { + if(*top == n) { + printf("\nStack is full. \n"); + } else { + arr[++(*top)] = i; + } +} + +int pop(int *arr, int *top) { + if(*top == -1) { + printf("\n Stack empty!\n"); + exit(1); + } else { + return(arr[(*top)--]); + } + return 0; +} From 8939a6fe39c7a97d0fec2caa8f789521be596ae7 Mon Sep 17 00:00:00 2001 From: szabopeter <1254135+szabopeter@users.noreply.github.com> Date: Sun, 14 Oct 2018 12:49:14 +0200 Subject: [PATCH 11/11] stack.py: Add IndexError Fixes https://github.com/NITSkmOS/Algorithms/issues/294 --- stack/Python/stack.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/stack/Python/stack.py b/stack/Python/stack.py index 8ae7ecf8..6c65f28b 100644 --- a/stack/Python/stack.py +++ b/stack/Python/stack.py @@ -24,8 +24,7 @@ def pop(self): """ if len(self.stack) <= 0: - # Raise an error if stack is empty. - return "No element in the Stack" + raise IndexError("No element in the Stack") else: return self.stack.pop()