## Archive for May, 2013

Binary Search is used to find a given key in a sorted array. In each step, the algorithm compares the search key value with the key value of the middle element of the array. If the keys match, then a matching element has been found and its index, or position, is returned. Otherwise, if the search key is less than the middle element’s key, then the algorithm repeats its action on the sub-array to the left of the middle element or, if the search key is greater, on the sub-array to the right. If the remaining array to be searched is empty, then the key cannot be found in the array and a special "not found" indication is returned.

Code

```        public static int BinarySearch(int[] input, int key)
{

int leftPointer = 0;
int length = input.Length;
int rightPointer = length - 1;
int middlePointer = 0;

while (rightPointer > leftPointer)
{
middlePointer = (rightPointer + leftPointer) / 2;

if (input[middlePointer] < key)
{
leftPointer = leftPointer + 1;
}
else if (input[middlePointer] > key)
{
rightPointer = rightPointer - 1;
}
else
{
return middlePointer;
}
}
return -1;
}```

Given a sorted array of integers and we have to find all Pythagorean triples.

Definition from Wikipedia : A Pythagorean triple consists of three positive integers a, b, and c, such that a2 + b2 = c2. Such a triple is commonly written (a, b, c), and a well-known example is (3, 4, 5).

Code :

```        public static void PythagoreanTriple(int[] input)
{

int length = input.Length;
if (length < 3)
{
Console.WriteLine("Length of Array can not be less then 3");
return;
}

for (int i = 0; i < length; i++)
{
input[i] = input[i] * input[i];
}

int leftPointer = 0;
int rightPointer = 0;
int temp = 0;
for (int i = length - 1; i > 1; i--)
{
leftPointer = 0;
rightPointer = i - 1;
temp = input[i]; ;
while (leftPointer < rightPointer)
{
if (input[leftPointer] + input[rightPointer] == temp)
{
Console.WriteLine(Math.Sqrt(input[leftPointer]) + ";"                                                     + Math.Sqrt(input[rightPointer])                                                     + ";" + Math.Sqrt(input[i]));
break;
}
else if (input[leftPointer] <= input[rightPointer])
{
leftPointer++;
}
else
{
rightPointer--;
}
}
}

}```
`Test Case: `
 Input Output { 1, 3, 4,5, 6, 7, 8, 10, 11 } 6;8;10 3;4;5 { 1, 3, 4,5, 6, 7, 8, 10, 11,12,13 } 5;12;13 6;8;10 3;4;5 { 5, 6, 7, 8, 10, 11,12,13,14,15,17 } 8;15;17 5;12;13 6;8;10

input : number of Rows

Output

```         *
*  *
*  *  *
*  *  *  *```
`Code`
```        public static void PrintStar(int rows)
{
int temp=rows;
for (int i = 1; i <= rows; i++)
{
for (int spacecounter = temp; spacecounter >= 1; spacecounter--)
{
Console.Write("   ");
}

for (int starCounter = 1; starCounter <= i; starCounter++)
{
Console.Write(" * ");
}
temp=temp-1;
Console.WriteLine("");
}
}```