Vijetha
BAN USER//C# Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BinarySearch
{
class Program
{
static void Main(string[] args)
{
int[] array = new int[6] { -10, -2, 0, 4, 6, 10 };
int index = ReturnIndex(array, 6, 0, array.Length-1);
if (index == -1)
{
Console.WriteLine("Element not found");
}
else
{
Console.WriteLine("Located at position {0}", index);
}
Console.Read();
}
public static int ReturnIndex(int[] array, int num, int start, int end)
{
if (end < start)
{
return -1;
}
else
{
int mid = end - start / 2;
if (num > array[mid])
{
return ReturnIndex(array, num, mid + 1, end);
}
else if (num < array[mid])
{
return ReturnIndex(array, num, start, mid - 1);
}
else
{
return mid;
}
}
}
}
}
Output:
Located at position 4
C# code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Sort2HalfSortedArrays
{
class Program
{
static void Main(string[] args)
{
int[] array = { 1, 3, 6, 8, -5, -2, 3, 8 };
int[] sortedArray = Sort(array); ;
Console.WriteLine("Sorted Array");
for (int i = 0; i < sortedArray.Length; i++)
{
Console.Write("{0} ", sortedArray[i]);
}
Console.Read();
}
public static int[] Sort(int[] array)
{
int i = 0;
while (array[i] < array[i + 1])
{
if (i + 1 == array.Length - 1)
{
return array;
}
else
{
i++;
}
}
int j = array.Length - 1;
while ((i >= 0) && i < j)
{
if (array[i] >= array[j])
{
int k = i;
while (k < j)
{
int temp = array[k];
array[k] = array[k + 1];
array[k + 1] = temp;
k++;
}
i--;
j -= 2;
}
else
{
j--;
}
}
return array;
}
}
}
output:
Sorted Array
-5,-2,1,3,3,6,8,8
Comment if any issues in this.
- Vijetha May 11, 2017