Consider the following approach An algorithm sorts an array
Solution
Hi buddy, please find the below java program
import java.util.*;
 import java.lang.*;
 import java.io.*;
class Main {
 //This method sorts the given array
 static void sort(int arr[]) {
 //Calculating the mid
 int mid = arr.length/2;
 //This loop iterates mid number of times
 for (int j = 0; j < mid; j++) {
 //Taking the left and right indices
 int left = j;
 int right = arr.length - j - 1;
 int min = Integer.MAX_VALUE;
 int minInd = 0;
 int max = Integer.MIN_VALUE;
 int maxInd = 0;
 //Calculating minimum and maximum valued indices in the left and right range
 for (int i = left; i <= right; i++) {
 if (arr[i] > max) {
 max = arr[i];
 maxInd = i;
 }
 if (arr[i] < min) {
 min = arr[i];
 minInd = i;
 }
 }
 //Replacing the left and right with min and max indices;
 int t = arr[left];
 arr[left] = arr[minInd];
 arr[minInd] = t;
 t = arr[right];
 arr[right] = arr[maxInd];
 arr[maxInd] = t;
 }
 }
 public static void main(String[] args) throws java.lang.Exception {
 int arr[] = {2,1,3,5,7,4,6,8};
 sort(arr);
 System.out.println(Arrays.toString(arr));
 }
 }
OUTPUT :
[1, 2, 3, 5, 4, 6, 7, 8]

