Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

JAVA Programming How would you take a given array of non-repeating random intege

ID: 3752411 • Letter: J

Question

JAVA Programming

How would you take a given array of non-repeating random integers and sort every 5th element. Meaning index 0 is the smallest element in the array. index 4 is the 5th smallest element in the array, index 9 is the 10th smallest element in the array and so on...

- this array could be small (like 5 indexes) or large (like 100,000 indexes).

- all other numbers do not change position

please help as soon as possible. all i need is the algorithm for partly sorting the array, not generating it.

Explanation / Answer

Save the below code as Sort5thEle.java.

//Sort5thEle.java

import java.util.Arrays;

public class Sort5thEle {

public static void sort_every_5th_element(int a[]) {

//looping through array and incrementing by 5

for(int i = 0 ; i<a.length; i+=5) {

// cloning the array into temp variable

int temp[] = a.clone();

//sorting the temp array

Arrays.sort(temp);

//geting the number at index

int j = temp[i];

//getting the actual index of number

int index = get_index(a,j);

//swapping the index in original array

int k = a[i];

a[index] = k;

a[i] = j;

if(i==0) i-=1;

}

}

//helper method for finding the index of element

private static int get_index(int a[],int val) {

int i;

for(i=0;i<a.length;i++) {

if(a[i]==val)break;

}

return i;

}

public static void main(String[] args) {

//a random array with unique element

int a[] = new int[]{3,1,2,8,4,5,6,9,17,10,19,12,15,13,99,23,34,41};

System.out.println("Before sorting every 5th Element ");

System.out.println(Arrays.toString(a));

System.out.println(" sorting .....");

sort_every_5th_element(a);

System.out.println(" After soting every 5th index ..");

System.out.println(Arrays.toString(a));

}

}

//OUTPUT

Before sorting every 5th Element
[3, 1, 2, 8, 4, 5, 6, 9, 17, 10, 19, 12, 15, 13, 99, 23, 34, 41]

sorting .....

After soting every 5th index ..
[1, 3, 2, 8, 5, 4, 6, 9, 17, 12, 19, 10, 15, 13, 23, 99, 34, 41]