0% found this document useful (0 votes)
32 views7 pages

Daa

The document contains C++ code to implement quicksort and print subsets of an array that sum to a given value. It defines functions for swapping elements, partitioning an array for quicksort, performing quicksort recursively, and printing subsets that sum to a given value from a sorted array. It then sorts an sample array using quicksort and prints subsets summing to 105, 100, and 95.

Uploaded by

Anjali
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)
32 views7 pages

Daa

The document contains C++ code to implement quicksort and print subsets of an array that sum to a given value. It defines functions for swapping elements, partitioning an array for quicksort, performing quicksort recursively, and printing subsets that sum to a given value from a sorted array. It then sorts an sample array using quicksort and prints subsets summing to 105, 100, and 95.

Uploaded by

Anjali
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/ 7

Q4.

#include <bits/stdc++.h>
using namespace std;
 
void swap(int* a, int* b) {
    int t = *a;
    *a = *b;
    *b = t;
}

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++;
            swap(&arr[i], &arr[j]);
        }
    }
    swap(&arr[i + 1], &arr[high]);
    return (i + 1);
}

void quickSort(int arr[], int low, int high) {


    if (low < high) {
        int pi = partition(arr, low, high);
        quickSort(arr, low, pi - 1);
        quickSort(arr, pi + 1, high);
    }
}

void printsubsets(int arr[], int l, int r, int sum) {


    while (r >= l) {
        if (arr[l] + arr[r] == sum) {
            cout << arr[l] << " " << arr[r] << endl;
            l = l + 1;
            r = r - 1;
        }
        if (arr[l] + arr[r] > sum)
            r = r - 1;
        if(arr[l] + arr[r] < sum)
            l = l + 1;
    }
}
int main()
{
    int arr[] = {76, 2 ,101, 24, 29, 71, 55};
    quickSort(arr, 0, 6);
    printsubsets(arr, 0, 6, 105);
    printsubsets(arr, 0, 6, 100);
    printsubsets(arr, 0, 6, 95);
    return 0;
}
// 2 24 29 55 71 76 101

Output :

You might also like