-
Notifications
You must be signed in to change notification settings - Fork 0
/
sortedarrayops.cs
81 lines (66 loc) · 1.7 KB
/
sortedarrayops.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
using System;
// To execute C#, please define "static void Main" on a class
// named Solution.
class Solution
{
static void Main(string[] args)
{
int[] arr = new int[10];
arr[0] = 12;
arr[1] = 16;
arr[2] = 20;
arr[3] = 40;
arr[4] = 50;
arr[5] = 70;
//int index = binarySearch(arr, 0, arr.Length, 4);
//Console.Write(index);
insertSorted(arr, 6, 26, 10);
for(int i=0; i<arr.Length; i++)
{
Console.Write(arr[i] + " ");
}
}
public static bool insertSorted(int[] arr, int index, int key, int capacity)
{
if(index >= capacity)
{
return false;
}
int i;
for(i = index -1; i>=0 && arr[i] > key; i--)
{
arr[i+1] = arr[i];
}
arr[i+1] = key;
return true;
}
public static int binarySearch(int[] arr, int low, int high, int key)
{
if(high < low)
return -1;
int mid = (low + high)/2;
if(arr[mid] == key)
{
return mid; //position
}
if(arr[mid] > key)
{
return binarySearch(arr, low, mid-1, key);
}
else
{
return binarySearch(arr, mid+1, high, key);
}
}
public static bool deleteelement(int[] arr, int key)
{
int index = binarySearch(arr, 0, arr.Length, key);
if(index == -1)
return false;
for(int pos=index; pos<arr.Length; pos++)
{
arr[pos] = arr[pos+1];
}
return true;
}
}