diff --git a/Programming/C#/Two sum b/Programming/C#/Two sum new file mode 100644 index 0000000..f9fd376 --- /dev/null +++ b/Programming/C#/Two sum @@ -0,0 +1,86 @@ + + +using System; + +class twosum { + static bool hasArrayTwoCandidates(int[] A, + int arr_size, int sum) + { + int l, r; + + + sort(A, 0, arr_size - 1); + + + l = 0; + r = arr_size - 1; + while (l < r) { + if (A[l] + A[r] == sum) + return true; + else if (A[l] + A[r] < sum) + l++; + else // A[i] + A[j] > sum + r--; + } + return false; + } + + + + + static int partition(int[] arr, int low, int high) + { + int pivot = arr[high]; + + + int i = (low - 1); + for (int j = low; j <= high - 1; j++) { + + if (arr[j] <= pivot) { + i++; + + + int temp = arr[i]; + arr[i] = arr[j]; + arr[j] = temp; + } + } + + + int temp1 = arr[i + 1]; + arr[i + 1] = arr[high]; + arr[high] = temp1; + + return i + 1; + } + + + static void sort(int[] arr, int low, int high) + { + if (low < high) { + + int pi = partition(arr, low, high); + + + sort(arr, low, pi - 1); + sort(arr, pi + 1, high); + } + } + + + public static void Main() + { + int[] A = { 1, 4, 45, 6, 10, -8 }; + int n = 16; + int arr_size = 6; + + if (hasArrayTwoCandidates(A, arr_size, n)) + Console.Write("Array has two elements" + + " with given sum"); + else + Console.Write("Array doesn't have " + + "two elements with given sum"); + } +} + +