Consider the following approach An algorithm sorts an array

Consider the following approach: An algorithm sorts an array of n elements by finding the smallest and largest elements and then exchanges those elements with the elements in the first and last positions in the array. Then the size of the array is reduced by two elements after excluding the two elements that are already in the proper positions, and the process is repeated on the remaining part of the array until the entire array is sorted. Write a code to implement the above algorithm. Write a driver program to show the novel sorting algorithm works correctly.

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]

 Consider the following approach: An algorithm sorts an array of n elements by finding the smallest and largest elements and then exchanges those elements with

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site