Ganges

Fun Algorithms

Binary Search works on sorted arrays by dividing the range in half on each step. Here's how to write it in Ganges.

app/main.ga

1   rama items = [10, 20, 30, 40, 50];

2   rama target = 30;

3   rama left = 0;

4   rama right = 4;

5   rama found = asatya;

7   chakra(left <= right) {

8     rama mid = (left + right) / 2;

10     yadi(items[mid] == target) {

11       rama found = satya;

12       rama left = right;

13     }

15     yadi(items[mid] < target) {

16       left = mid + 1;

17     } anyatha {

18       right = mid - 1;

19     }

20   }

22   vadha(found);

$ Terminal (zsh)

>> SATYA

Sorted Array

Binary search requires a sorted array. Without it, the divide-and-conquer logic breaks.

Mid Point

mid = (left + right) / 2 divides the array into two. Search continues in the correct half.

Conditional Logic

If item is greater, shift left to mid + 1. If smaller, shift right to mid - 1. Use viram to exit on match.

Recursion

Functions in Ganges can call themselves recursively. Use this to solve problems like factorials, Fibonacci numbers, and tree traversals.

app/main.ga

1   rama factorial = kriya (n) {

2     yadi(n == 0) {

3       daan 1;

4     }

5     daan n * factorial(n - 1);

6   }

8   vadha(factorial(5));

$ Terminal (zsh)

>> 120

Base Case

Every recursive function needs a base case to prevent infinite calls. Here, n == 0 returns 1.

Recursive Step

The function calls itself with n - 1, reducing the problem step by step.

Return Keyword

Use daan to return values from functions. This is how recursion bubbles back results.