Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Partition a Array

Tags:

c

Given a randomly ordered array (arr) of n elements, function partitionArray(int arr[], int n, int x) partition the elements into two subsets such that elements <= x are in left subset and elements > x are in the right subset.

The first line of the test case will contain two numbers n (number of elements in a list ) and x (number to use for partition) separated by space. The next line will contain N space-separated integers.

I am getting the wrong output for certain cases from the following Function.

Here's my code:

void partitionArray(int arr[], int n, int x)
{
    int i, j, temp;
    i = 0;
    j = n-1;
  
    while (i < j)
    {
        while (arr[i] <=x)
            i++;
        while (arr[j] > x)
            j--;
    
        temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    
        i++;
        j--;
    }  
}

For the cases I am getting the right output is:

10 6
28 26 25 5 6 7 24 29 6 10

For the cases I am not getting the right output is:

10 17
28 26 25 11 16 12 24 29 6 10

The output I am getting in this:

10
6
12
11
25
16
24
29
26
28

Expected Output:

10
6
12
11
16
25
24
29
26
28
10 6
28 26 25 11 5 7 24 29 6 10

The output I am getting in this:

6
25
5
11
26
7
24
29
28
10

Expected Output:

6
5
25
11
26
7
24
29
28
10

Can Anyone help me this

like image 834
deveop Avatar asked May 24 '21 02:05

deveop


People also ask

What does partition an array mean?

Definition: (1) A division of a set into nonempty disjoint sets that completely cover the set. (2) To rearrange the elements of an array into two (or more) groups, typically, such that elements in the first group are less than a value and elements in the second group are greater.

How do you divide an array into two parts?

To divide an array into two, we need at least three array variables. We shall take an array with continuous numbers and then shall store the values of it into two different variables based on even and odd values.

How do I partition an array in Python?

partition() in Python. numpy. partition() function is used to create a partitioned copy of input array with its elements rearranged in such a way that the value of the element in k-th position is in the position it would be in a sorted array.


Video Answer


1 Answers

Below change will do:

if(i < j){
    temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;
}

When swapping when the value of j is i+1 and arr[i]<x and arr[j]>x, after i++ and j-- from while loops, the value of j is i-1 in your code. Hence checking i<j before swapping is important.

Suppose input is

2 5
1 10

Your output will be

10 1

And the index has to be checked as index may run out of the size of the array.

while (i<n && arr[i]<=x)
    i++;
while (j>=0 && arr[j]>x)
    j--;

Example inputs:

5 7
5 3 2 4 1

5 3
7 6 9 5 6
like image 103
Revathi Polisetty Avatar answered Oct 13 '22 22:10

Revathi Polisetty