Pages

arrange elements in array based on pivot value

Arrange elements in array based on particular value

  • In a given integer array, arrange value to left and right side of array based on a particular value (say pivot).
  • values less than pivot will arrange on the left side of the array and values greater than pivot will arrange on the right side of the array
Examples:

Input: { 4, 9, 7, 6, 3, 2, 8, 9, 1 }
o/p:    4 3 2 1 6 9 8 7 9 

Input: { 4, 9, 7, 6, 3, 2, 8, 5, 1 }
o/p:    4 3 2 5 1 6 8 7 9

Here pivot=6. so values less than pivot will arrange to left and values greater than pivot will arrange to the right of the array.

Program:
public class arrangeArrayParticularValue {
public static void main(String[] args) {
int[] arr = { 4, 9, 7, 6, 3, 2, 8, 5, 1 };
int pivot = 6;
// new array to store values in arranged order
int[] b = new int[arr.length];
// starting index for new array
int k = 0;
// last position of new array
int max = arr.length - 1;
// loop - to arrange values to left side
for (int i = 0; i <= arr.length - 1; i++) {
if (arr[i] < pivot) {
b[k] = arr[i];
k++;
}
}

// after left arrange completed - then add pivot value
b[k] = pivot;
k++;

// after pivot added, loop - to arrange values to right side
for (int i = 0; i <= arr.length - 1; i++) {
if (arr[i] > pivot) {
b[max] = arr[i];
//adding values from last index
max--;
}
}

// printing arranged array
for (int n : b) {
System.out.
print(n + " ");
}
}
}
Output:
arrange elements in array based on pivot value
arrange elements in an array based on pivot value

Please comment below to feedback or ask questions.

No comments:

Post a Comment

Please comment below to feedback or ask questions.