0% found this document useful (0 votes)
45 views36 pages

Algoithms Notes pt2

The document contains code for several sorting and searching algorithms: 1) A binary search function that searches for a target value in a sorted array and returns its index. 2) A function that counts the number of pairs in a sorted array with a difference of k. 3) A function that finds the pair of elements in a sorted array with the minimum absolute difference to a given sum x.

Uploaded by

Natalie Song
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
45 views36 pages

Algoithms Notes pt2

The document contains code for several sorting and searching algorithms: 1) A binary search function that searches for a target value in a sorted array and returns its index. 2) A function that counts the number of pairs in a sorted array with a difference of k. 3) A function that finds the pair of elements in a sorted array with the minimum absolute difference to a given sum x.

Uploaded by

Natalie Song
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 36

/* Standard binary search function */

int binarySearch(int arr[], int low, int high, int x)


{
    if (high >= low)
    {
        int mid = low + (high - low)/2;
        if (x == arr[mid])
            return mid;
        if (x > arr[mid])
            return binarySearch(arr, (mid + 1), high, x);
        else
            return binarySearch(arr, low, (mid -1), x);
    }
    return -1;
}
 
/* Returns count of pairs with difference k in arr[] of size n. */
int countPairsWithDiffK(int arr[], int n, int k)
{
    int count = 0, i;
    sort(arr, arr+n);  // Sort array elements
 
    /* code to remove duplicates from arr[] */
   
    // Pick a first element point
    for (i = 0; i < n; i++){
      while(i - 1 >= 0 && arr[i] == arr[i - 1]) i++;
   
        if (binarySearch(arr, i+1, n-1, arr[i] + k) != -1)
            count++;
    }
 
    return count;
}

1) Initialize a variable diff as infinite (Diff is used to store the


difference between pair and x). We need to find the minimum diff.
2) Initialize two index variables l and r in the given sorted array.
(a) Initialize first to the leftmost index: l = 0
(b) Initialize second the rightmost index: r = n-1
3) Loop while l < r.
(a) If abs(arr[l] + arr[r] - sum) < diff then
update diff and result
(b) If(arr[l] + arr[r] < sum ) then l++
(c) Else r--
void printClosest(int arr[], int n, int x)
{
    int res_l, res_r;  // To store indexes of result pair
 
    // Initialize left and right indexes and difference between
    // pair sum and x
    int l = 0, r = n-1, diff = INT_MAX;
 
    // While there are elements between l and r
    while (r > l)
    {
       // Check if this pair is closer than the closest pair so far
       if (abs(arr[l] + arr[r] - x) < diff)
       {
           res_l = l;
           res_r = r;
           diff = abs(arr[l] + arr[r] - x);
       }
 
       // If this pair has more sum, move to smaller values.
       if (arr[l] + arr[r] > x)
           r--;
       else // Move to larger values
           l++;
    }
 
    cout <<" The closest pair is " << arr[res_l] << " and " << arr[res_r];
}
// A utility method to swap two numbers.
void swap(int *x, int *y)
{
    int temp = *x;
    *x = *y;
    *y = temp;
}
 
// This function sorts arr[0..n-1] in wave form, i.e.,
// arr[0] >= arr[1] <= arr[2] >= arr[3] <= arr[4] >= arr[5]..
void sortInWave(int arr[], int n)
{
    // Sort the input array
    sort(arr, arr+n);
 
    // Swap adjacent elements
    for (int i=0; i<n-1; i += 2)
        swap(&arr[i], &arr[i+1]);
}
 
// a utility function that returns total set bits count in an integer
int countBits(int a)
{
    int count = 0;
    while (a) {
        if (a & 1)
            count += 1;
        a = a >> 1;
    }
    return count;
}
 
// Function to simultaneously sort both arrays using insertion sort
// https://www.geeksforgeeks.org/insertion-sort/ )
void insertionSort(int arr[], int aux[], int n)
{
    for (int i = 1; i < n; i++) {
        // use 2 keys because we need to sort both arrays simultaneously
        int key1 = aux[i];
        int key2 = arr[i];
        int j = i - 1;
 
        // Move elements of arr[0..i-1] and aux[0..i-1],
        // such that elements of aux[0..i-1] are greater
        // than key1, to one position ahead of their current
        // position
        while (j >= 0 && aux[j] < key1) {
            aux[j + 1] = aux[j];
            arr[j + 1] = arr[j];
            j = j - 1;
        }
        aux[j + 1] = key1;
        arr[j + 1] = key2;
    }
}
 
// Function to sort according to bit count using an auxiliary array
void sortBySetBitCount(int arr[], int n)
{
    // Create an array and store count of set bits in it.
    int aux[n];
    for (int i = 0; i < n; i++)
        aux[i] = countBits(arr[i]);
 
    // Sort arr[] according to values in aux[]
    insertionSort(arr, aux, n);
}
 
// Utility function to print an array
void printArr(int arr[], int n)
{
    for (int i = 0; i < n; i++)
        printf("%d ", arr[i]);
}

You might also like