= val) {
37 |
38 | mid = lo + ((val - nums[lo]) * (hi - lo)) / (nums[hi] - nums[lo]);
39 | if (nums[mid] < val) {
40 | lo = mid + 1;
41 |
42 | } else if (nums[mid] > val) {
43 | hi = mid - 1;
44 |
45 | } else return mid;
46 | }
47 |
48 | if (nums[lo] == val) return lo;
49 |
50 | return -1;
51 | }
52 |
53 | }
54 |
--------------------------------------------------------------------------------
/Sorting Algorithms/Python/bucket_sort.py:
--------------------------------------------------------------------------------
1 | # Python program to sort array
2 | # of elements using Bucket Sort
3 |
4 | # Insertion sort algo
5 | def ins_sort_algorithm(elem):
6 | for i in range(1, len(elem)):
7 | j = i-1
8 | inc = elem[i]
9 | while j >= 0 and elem[j] > inc:
10 | elem[j+1] = elem[j]
11 | j -= 1
12 | elem[j+1] = inc
13 | return elem
14 |
15 | # Bucket sort algo
16 | def bucket_sort_algorithm(val_list):
17 | temp = []
18 | slot = 8 # customizable
19 | # add empty lists to temp(_arr)
20 | for i in range(slot):
21 | temp.append([])
22 | # Computing
23 | for j in val_list:
24 | index_b = int(slot * j)
25 | temp[index_b].append(j)
26 |
27 | for i in range(slot):
28 | temp[i] = ins_sort_algorithm(temp[i])
29 |
30 | k = 0
31 | for i in range(slot):
32 | for j in range(len(temp[i])):
33 | val_list[k] = temp[i][j]
34 | k += 1
35 | return val_list
36 |
37 | # Driver Function
38 | elem_li = [0.1290, 0.2523, 0.0001, 0.91, 0.454, 0.978, 0.01, 0.66]
39 | # Original
40 | print("Before Sorting: ")
41 | print(elem_li)
42 | # Result
43 | print("Result(post-Bucket Sort): ")
44 | print(bucket_sort_algorithm(elem_li))
45 |
46 | # Expected Outcome:
47 | # ----------------
48 | # Before Sorting:
49 | # [0.129, 0.2523, 0.0001, 0.91, 0.454, 0.978, 0.01, 0.66]
50 | # Result(post-Bucket Sort):
51 | # [0.0001, 0.01, 0.129, 0.2523, 0.454, 0.66, 0.91, 0.978]
--------------------------------------------------------------------------------
/Search Algorithms/Dlang/binary.d:
--------------------------------------------------------------------------------
1 | /*
2 | binary search must receive an ordered array!
3 | */
4 | int binarySearch( int[] haystack, int needle )
5 | {
6 | size_t start = 0;
7 | size_t end = haystack.length;
8 | while( start < end)
9 | {
10 | size_t index = (start + end ) / 2;
11 | if( haystack[index] == needle ) return index;
12 | if( needle > haystack[index] )
13 | start = index + 1;
14 | else
15 | end = index;
16 | }
17 | return -1;
18 | }
19 |
20 | void main()
21 | {
22 | import std.random : uniform;
23 | import std.stdio : writeln, readln;
24 | import std.conv : to;
25 | import std.string : strip;
26 | import std.algorithm : sort;
27 | import std.array : array;
28 |
29 | int[] haystack;
30 |
31 | size_t haystack_size = 100;
32 | size_t rnd_low_bound = 0;
33 | size_t rnd_high_bound = 100;
34 |
35 | haystack.length = haystack_size;
36 |
37 | //fill array randomly
38 | foreach(index ; 0 .. haystack_size)
39 | {
40 | haystack[index] = cast(int) uniform(rnd_low_bound, rnd_high_bound);
41 | }
42 |
43 | //choose needle
44 | writeln("Choose a integer value between ", rnd_low_bound, " and ", rnd_high_bound , " :");
45 | int needle = readln().strip.to!int;
46 |
47 | haystack = haystack.sort.array;
48 |
49 | int result = binarySearch( haystack, needle );
50 |
51 | if( result == -1 ){
52 | writeln("The value was not found!");
53 | } else {
54 | writeln("The first occurence of the value are in the ", result, " position of the array");
55 | }
56 |
57 | writeln("Array Values:");
58 | writeln(haystack);
59 | }
--------------------------------------------------------------------------------
/Sorting Algorithms/php/mergesort.php:
--------------------------------------------------------------------------------
1 | 0 || count(right) > 0){
40 | if(count($left) > 0 && count(right) > 0){
41 | if($left[0] <= $right[0]){
42 | $result[] = array_shift($left);
43 | } else {
44 | $result[] = array_shift($right);
45 | }
46 | } elseif (count($left) > 0){
47 | $result[] = array_shift($left);
48 | } elseif (count($right) > 0){
49 | $result[] = array_shift($right);
50 | }
51 | }
52 |
53 | print_array($result);exit;
54 |
55 | return $result;
56 | }
57 |
58 | function print_array($array){
59 | echo "";
60 | print_r($array);
61 | echo "
";
62 | echo "
";
63 | }
64 |
65 | ?
66 |
--------------------------------------------------------------------------------
/Greedy Algorithms/Fractional-Knapsack.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 | #include
5 | int main() {
6 |
7 | std::cout << "Enter number of objects available = ";
8 | int n;
9 | std::cin>>n;
10 |
11 | std::cout << "Enter Value and Weight of all objects:" << '\n';
12 | std::vector > v(n);
13 | for(int i=0;i>v[i].first;
16 | std::cout<<"Weight["<>v[i].second;
18 | }
19 |
20 | std::cout<<"Enter Capacity of Bag : ";
21 | double W;
22 | std::cin>>W;
23 |
24 | std::vector > valbwe(n); //value by weight
25 | for(int i=0;i Selected(n,false);
32 | double profit=0;
33 | for(int i=0;i0){
35 | if(W>v[valbwe[i].second].second){
36 | profit+=v[valbwe[i].second].first;
37 | W-=v[valbwe[i].second].second;
38 | }
39 | else{
40 | profit+=(v[valbwe[i].second].first * (W))/v[valbwe[i].second].second;
41 | W = 0;
42 | }
43 | Selected[valbwe[i].second] = true;
44 | }
45 | else{
46 | break;
47 | }
48 | }
49 |
50 | std::cout << "Selected Objects :" << '\n';
51 | for(int i=0;i
2 |
3 | using namespace std;
4 |
5 | void preKMP(string pattern, int f[])
6 | {
7 | int m = pattern.length(), k;
8 | f[0] = -1;
9 | for (int i = 1; i < m; i++)
10 | {
11 | k = f[i - 1];
12 | while (k >= 0)
13 | {
14 | if (pattern[k] == pattern[i - 1])
15 | break;
16 | else
17 | k = f[k];
18 | }
19 | f[i] = k + 1;
20 | }
21 | }
22 |
23 | bool KMP(string pattern, string target)
24 | {
25 | int m = pattern.length();
26 | int n = target.length();
27 | int f[m];
28 | preKMP(pattern, f);
29 | int i = 0;
30 | int k = 0;
31 | while (i < n)
32 | {
33 | if (k == -1)
34 | {
35 | i++;
36 | k = 0;
37 | }
38 | else if (target[i] == pattern[k])
39 | {
40 | i++;
41 | k++;
42 | if (k == m)
43 | return 1;
44 | }
45 | else
46 | k = f[k];
47 | }
48 | return 0;
49 | }
50 |
51 | int main()
52 | {
53 | string tar = "this is an algo for hacktoberfest";
54 | string pat = "hack";
55 | if (KMP(pat, tar))
56 | cout<<"'"<> permute(int[] arr){
12 | List> list = new ArrayList<>();
13 | int[] index = new int[arr.length];
14 | int n = index.length;
15 | int fact = 1;
16 |
17 | for(int i=0; i());
24 | }
25 |
26 | int listIndex = fact-1;
27 | list.set(listIndex, toList(arr));
28 | listIndex--;
29 |
30 | int i = 0;
31 | while(i < n){
32 | if(index[i] < i){
33 | int j = i%2 == 0 ? 0: index[i];
34 |
35 | int temp = arr[j];
36 | arr[j] = arr[i];
37 | arr[i] = temp;
38 | list.set(listIndex, toList(arr));
39 | listIndex--;
40 | index[i]++;
41 | i = 0;
42 | }else{
43 | index[i] = 0;
44 | i++;
45 | }
46 | }
47 | return list;
48 | }
49 |
50 | public static List toList(int[] arr){
51 | List list = new ArrayList<>();
52 | for(int i=arr.length-1; i>=0; i--){
53 | list.add(arr[i]);
54 | }
55 | return list;
56 | }
57 | }
--------------------------------------------------------------------------------
/Dynamic Programming/n-queen.cpp:
--------------------------------------------------------------------------------
1 | #define N 4
2 | #include
3 | #include
4 | void printSolution(int board[N][N])
5 | {
6 | for (int i = 0; i < N; i++) {
7 | for (int j = 0; j < N; j++)
8 | printf(" %d ", board[i][j]);
9 | printf("\n");
10 | }
11 | }
12 |
13 | bool isSafe(int board[N][N], int row, int col)
14 | {
15 | int i, j;
16 |
17 | for (i = 0; i < col; i++)
18 | if (board[row][i])
19 | return false;
20 | for (i = row, j = col; i >= 0 && j >= 0; i--, j--)
21 | if (board[i][j])
22 | return false;
23 | for (i = row, j = col; j >= 0 && i < N; i++, j--)
24 | if (board[i][j])
25 | return false;
26 |
27 | return true;
28 | }
29 | bool solveNQUtil(int board[N][N], int col)
30 | {
31 | if (col >= N)
32 | return true;
33 | for (int i = 0; i < N; i++) {
34 | if (isSafe(board, i, col)) {
35 | board[i][col] = 1;
36 | if (solveNQUtil(board, col + 1))
37 | return true;
38 | board[i][col] = 0; // BACKTRACK
39 | }
40 | }
41 | return false;
42 | }
43 | bool solveNQ()
44 | {
45 | int board[N][N] = { { 0, 0, 0, 0 },
46 | { 0, 0, 0, 0 },
47 | { 0, 0, 0, 0 },
48 | { 0, 0, 0, 0 } };
49 |
50 | if (solveNQUtil(board, 0) == false) {
51 | printf("Solution does not exist");
52 | return false;
53 | }
54 |
55 | printSolution(board);
56 | return true;
57 | }
58 | int main()
59 | {
60 | solveNQ();
61 | return 0;
62 | }
--------------------------------------------------------------------------------
/Graph/dfs_and_bfs.cpp:
--------------------------------------------------------------------------------
1 | // LANGUAGE: C++
2 | // ENV: gcc
3 | //AUTHOR: Proma Roy
4 | //GITHUB: https://github.com/promaroy
5 |
6 |
7 | // implementing a undirected graph data structure using adjacency list and traversals...
8 |
9 | #include
10 | using namespace std;
11 | vector v[6]; //an array of vectors to store the nodes connected to a node...
12 | int vis[6]={0}; // a hash array to keep track of the nodes which are already visited
13 | queue q;//to implement bfs..
14 | int level[6]={0};
15 | void add_edge(int a,int b)// function to add an edge
16 | {
17 | v[a].push_back(b);
18 | v[b].push_back(a);
19 | }
20 | void dfs(int in)//function to run dfs traversal
21 | {
22 | vis[in]=1;
23 | cout<
2 |
3 | using namespace std;
4 |
5 | void BinaryInsertion(int *v, int n)
6 | {
7 | int i,j,temp,medio,izq,der;
8 | for (j = 1; j < n; j++)
9 | {
10 | //Se declaran las variables de comparacion y la auxiliar para desplazar los valores ordenados
11 | temp=v[j];
12 | izq=0;
13 | der = j-1;
14 | //Se busca la posición de la inserción de forma binaria
15 | while (izq <= der)
16 | {
17 | medio = (int) ((izq + der)/2);
18 | if (temp <= v[medio])
19 | der = medio-1;
20 | else
21 | izq = medio+1;
22 | }
23 | //Los elementos ya ordenados de desplazan a la derecha(final)
24 | for (i = j-1; i>= izq; i--)
25 | v[i+1] = v[i];
26 | v[izq] = temp;
27 | }
28 | }
29 |
30 | void mostrarDatos(int v[],int lim){//Se muestran los datos del vector
31 | int contador=1;
32 | for (int i = 0; i < lim; i++){
33 | cout<<"Valor del elemento No."<>n;
44 | /*Declaración del vector a ordenar*/
45 | int v[n];
46 |
47 | //Rellenado de vector
48 | for (int i = 0; i < n; i++){
49 | cout<<"Ingrese el elemento: ";
50 | cin>>x;
51 | v[i]=x;
52 | }
53 |
54 |
55 | cout<<"Valores no ordenados"<
5 | #include
6 |
7 |
8 | void merge(int arr[], int l, int m, int r)
9 | {
10 | int i, j, k;
11 | int n1 = m - l + 1;
12 | int n2 = r - m;
13 |
14 | int L[n1], R[n2];
15 | for (i = 0; i < n1; i++)
16 | L[i] = arr[l + i];
17 | for (j = 0; j < n2; j++)
18 | R[j] = arr[m + 1 + j];
19 |
20 | i = 0;
21 | j = 0;
22 | k = l;
23 | while (i < n1 && j < n2)
24 | {
25 | if (L[i] <= R[j])
26 | {
27 | arr[k] = L[i];
28 | i++;
29 | }
30 | else
31 | {
32 | arr[k] = R[j];
33 | j++;
34 | }
35 | k++;
36 | }
37 |
38 | while (i < n1)
39 | {
40 | arr[k] = L[i];
41 | i++;
42 | k++;
43 | }
44 |
45 |
46 | while (j < n2)
47 | {
48 | arr[k] = R[j];
49 | j++;
50 | k++;
51 | }
52 | }
53 |
54 |
55 | void mergeSort(int arr[], int l, int r)
56 | {
57 | if (l < r)
58 | {
59 | int m = l + (r - l) / 2;
60 |
61 | mergeSort(arr, l, m);
62 | mergeSort(arr, m + 1, r);
63 |
64 | merge(arr, l, m, r);
65 | }
66 | }
67 |
68 | void printArray(int A[], int size)
69 | {
70 | int i;
71 | for (i = 0; i < size; i++)
72 | printf("%d ", A[i]);
73 | printf("\n");
74 | }
75 |
76 | int main()
77 | {
78 | int arr[] = {12, 11, 13, 5, 6, 7};
79 | int arr_size = sizeof(arr) / sizeof(arr[0]);
80 |
81 | printf("Given array is \n");
82 | printArray(arr, arr_size);
83 |
84 | mergeSort(arr, 0, arr_size - 1);
85 |
86 | printf("\nSorted array is \n");
87 | printArray(arr, arr_size);
88 | return 0;
89 | }
--------------------------------------------------------------------------------
/Sorting Algorithms/Python/ShellSort.py:
--------------------------------------------------------------------------------
1 | ##Shell sort
2 | **It is an in-place comparison sort.**
3 | ***This algorithm is based on sorting pairs of elements far apart from each other, by progressively reducing the gap between elements to be compared. Starting with far apart elements, algorithm moves some out-of-place elements into position faster than a simple nearest neighbor exchange.***
4 | ###Time complexity
5 | **The running time of Shellsort is heavily dependent on the gap sequence it uses.**
6 | -Worst complexity: Depends on gap sequence
7 | -Average complexity: n*log(n)^2 or n^(3/2)
8 | -Best complexity: n
9 |
10 | ##Python Code implementation of Shell sort
11 |
12 | >def shellSort(arr):
13 | > # start with large gap and then reduce it to smaller one
14 | >n=len(arr)
15 | >gap=n/2
16 |
17 | > # perform gapped insertion sort for this gap size.
18 | > # The first gapped elements are already in Gap
19 | > # Order keep adding till the end of array
20 | > # is gap sorted
21 |
22 | > while gap>0:
23 | > for j in range(gap,n):
24 | > # add a[j] to the elements that have been gap sorted
25 | > # then,save a[j] in temp and make a hole at position j
26 | > temp=arr[j]
27 |
28 | > # shift earlier gap-sorted elements up until the correct location for a[j] is found
29 |
30 | > k=j
31 | > while k >= gap and arr[k-gap] >temp:
32 | >arr[k] = arr[k-gap]
33 | > k -= gap
34 |
35 | > # put temp (the original a[j]) in its correct location
36 | > arr[k] = temp
37 | >gap /= 2
38 |
39 | > #main program
40 | > arr = [ 12, 34, 54, 2, 3]
41 |
42 | >n = len(arr)
43 | >print ("Array before sorting:")
44 | >for i in range(n):
45 | >print(arr[i]),
46 |
47 | >shellSort(arr)
48 |
49 | >print ("\nArray after sorting:")
50 | >for i in range(n):
51 | >print(arr[i])
52 |
53 | ##thanks for reading!
54 |
55 |
56 |
57 |
--------------------------------------------------------------------------------
/Backtracking/SumOfSubsets.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 |
4 | #define ARRAYSIZE(a) (sizeof(a))/(sizeof(a[0]))
5 |
6 | static int total_nodes;
7 | // prints subset found
8 | void printSubset(int A[], int size)
9 | {
10 | for(int i = 0; i < size; i++)
11 | {
12 | printf("%*d", 5, A[i]);
13 | }
14 |
15 | printf("n");
16 | }
17 |
18 | // inputs
19 | // s - set vector
20 | // t - tuplet vector
21 | // s_size - set size
22 | // t_size - tuplet size so far
23 | // sum - sum so far
24 | // ite - nodes count
25 | // target_sum - sum to be found
26 | void subset_sum(int s[], int t[],
27 | int s_size, int t_size,
28 | int sum, int ite,
29 | int const target_sum)
30 | {
31 | total_nodes++;
32 | if( target_sum == sum )
33 | {
34 | // We found subset
35 | printSubset(t, t_size);
36 | // Exclude previously added item and consider next candidate
37 | subset_sum(s, t, s_size, t_size-1, sum - s[ite], ite + 1, target_sum);
38 | return;
39 | }
40 | else
41 | {
42 | // generate nodes along the breadth
43 | for( int i = ite; i < s_size; i++ )
44 | {
45 | t[t_size] = s[i];
46 | // consider next level node (along depth)
47 | subset_sum(s, t, s_size, t_size + 1, sum + s[i], i + 1, target_sum);
48 | }
49 | }
50 | }
51 |
52 | // Wrapper to print subsets that sum to target_sum
53 | // input is weights vector and target_sum
54 | void generateSubsets(int s[], int size, int target_sum)
55 | {
56 | int *tuplet_vector = (int *)malloc(size * sizeof(int));
57 |
58 | subset_sum(s, tuplet_vector, size, 0, 0, 0, target_sum);
59 |
60 | free(tuplet_vector);
61 | }
62 |
63 | int main()
64 | {
65 | int weights[] = {10, 7, 5, 18, 12, 20, 15};
66 | int size = ARRAYSIZE(weights);
67 |
68 | generateSubsets(weights, size, 35);
69 | printf("Nodes generated %dn", total_nodes);
70 | return 0;
71 | }
72 |
--------------------------------------------------------------------------------
/Greedy Algorithms/Job Sequencing.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | using namespace std;
3 |
4 | struct JOB{
5 |
6 | char job;
7 | int dline;
8 | int profit;
9 | };
10 |
11 | bool comparision(JOB a,JOB b){
12 | return (a.profit>b.profit);
13 | }
14 |
15 | void job_Sequencing(struct JOB a[],int n){
16 |
17 | sort(a,a+n,comparision); //max to min Profit
18 |
19 | //Finding max deadline => MAX Size of output Array
20 |
21 | int max_deadline=0;
22 | for(int i=0;imax_deadline){
24 | max_deadline=a[i].dline;
25 | }
26 | }
27 | //cout<=1){
44 | output[x]=a[i].job;
45 | }
46 | }
47 | }
48 |
49 | for(int i=1;i<=max_deadline;i++){
50 | if(output[i]!='?'){
51 | cout<