public class FirstMaxFirstMin {
void rearrange(int arr[], int n)
{
// Auxiliary array to hold modified array
int temp[] = new int[n];
// Indexes of smallest and largest elements
// from remaining array.
int small=0, large=n-1;
// To indicate whether we need to copy remaining
// largest or remaining smallest at next position
boolean flag = true;
// Store result in temp[]
for (int i=0; i<n; i++)
{
if (flag)
temp[i] = arr[large--];
else
temp[i] = arr[small++];
flag = !flag;
}
// Copy temp[] to arr[]
for (int i=0; i<n; i++)
arr[i] = temp[i];
}
public static void main(String[] args) {
int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int n = arr.length;
FirstMaxFirstMin f=new FirstMaxFirstMin();
System.out.println("Original Array");
for (int i = 0; i < n; i++)
System.out.print(arr[i]+" ");
f.rearrange(arr, n);
System.out.println("\nModified Array");
for (int i = 0; i < n; i++)
System.out.print(arr[i]+" ");
}
}
Output:
Original Array
1 2 3 4 5 6 7 8 9
Modified Array
9 1 8 2 7 3 6 4 5
void rearrange(int arr[], int n)
{
// Auxiliary array to hold modified array
int temp[] = new int[n];
// Indexes of smallest and largest elements
// from remaining array.
int small=0, large=n-1;
// To indicate whether we need to copy remaining
// largest or remaining smallest at next position
boolean flag = true;
// Store result in temp[]
for (int i=0; i<n; i++)
{
if (flag)
temp[i] = arr[large--];
else
temp[i] = arr[small++];
flag = !flag;
}
// Copy temp[] to arr[]
for (int i=0; i<n; i++)
arr[i] = temp[i];
}
public static void main(String[] args) {
int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int n = arr.length;
FirstMaxFirstMin f=new FirstMaxFirstMin();
System.out.println("Original Array");
for (int i = 0; i < n; i++)
System.out.print(arr[i]+" ");
f.rearrange(arr, n);
System.out.println("\nModified Array");
for (int i = 0; i < n; i++)
System.out.print(arr[i]+" ");
}
}
Output:
Original Array
1 2 3 4 5 6 7 8 9
Modified Array
9 1 8 2 7 3 6 4 5
No comments:
Post a Comment