Partition Array Around Pivot

This program partitions an array around a pivot element.

Problem Statement

Write a Java program to partition an integer array around pivot 5.

Source Code

1 public class PartitionAroundPivot {
2 public static void main(String[] args) {
3 System.out.println("Eduinq Partition Around Pivot");
4 int[] arr = {7,2,9,4,5,1};
5 int pivot=5;
6 String less="", greater="";
7 for(int num:arr){
8 if(num<pivot) less+=num+" ";
9 else if(num>pivot) greater+=num+" ";
10 }
11 System.out.println("Less than pivot: "+less);
12 System.out.println("Greater than pivot: "+greater);
13 }
14 }

Program Output

Eduinq Partition Around Pivot
Less than pivot: 2 4 1 
Greater than pivot: 7 9 

Explanation

A loop iterates through the array comparing each number with the pivot value, appending it to a less or greater string as appropriate, demonstrating pivot-based partitioning of an array.

Quick Links to Explore