Skip to content
This repository has been archived by the owner on Oct 14, 2021. It is now read-only.

Two sum #459 #552

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
86 changes: 86 additions & 0 deletions Programming/C#/Two sum
Original file line number Diff line number Diff line change
@@ -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");
}
}