In: Computer Science
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
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
// 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
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("\nsorting .....");
sort_every_5th_element(a);
System.out.println("\nAfter 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]