Rearrange Positive and Negative Numbers in Array Without Extra Space

package org.wesome.dsalgo;

public class RearrangePositiveNegative {
    public static int[] reArrangePositiveNegative(int[] arr) {
        int indx2 = 0;
        int pivot = 0;

        for (int indx1 = 0; indx1 < arr.length; indx1++) {
            if (arr[indx1] < pivot) {
                swap(arr, indx1, indx2);
                indx2++;
            }
        }
        return arr;
    }

    private static void swap(int[] arr, int indx1, int indx2) {

        arr[indx1] = arr[indx1] ^ arr[indx2];
        arr[indx2] = arr[indx1] ^ arr[indx2];
        arr[indx1] = arr[indx1] ^ arr[indx2];
    }
}
package org.wesome.dsalgo;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

import static org.wesome.dsalgo.RearrangePositiveNegative.reArrangePositiveNegative;

public class RearrangePositiveNegativeTest {
    @Test
    public void reArrangePositiveNegativeTest() {
        int[] arr = {9, -3, 5, -2, -8, -6, 1, 3};
        int[] arrResponse = {-3, -2, -8, -6, 5, 9, 1, 3};
        Assertions.assertArrayEquals(arrResponse, reArrangePositiveNegative(arr));
    }
}
plugins {
    id 'java'
    id "io.freefair.lombok" version "6.2.0"
}

group = 'org.wesome'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = JavaVersion.VERSION_1_8

configurations {
    compileOnly {
        extendsFrom annotationProcessor
    }
}

repositories {
    mavenCentral()
}

dependencies {
    testImplementation 'org.junit.jupiter:junit-jupiter:5.6.2'
}

test {
    useJUnitPlatform()
}

 

follow us on