Hi there guys,
I seem to be having a problem with my java code.
Scenario;
I have an array, this is generated according to the user; entering 200; will give him 200 numbers. These numbers are supposed to be semi sorted. To achieve this i created a random array, then sorted it.
But now the problem is; its supposed to be semi sorted; for example;
My code generates me an array of size 8. [1,2,3,4,5,6,7,8]... NO PROBLEM HERE!
PROBLEM HERE --> What the code should ideally do? -- User puts in the amount of numbers he wants to move around. E.g. 2, this means he wants 2 random numbers to be moved randomly in the array.
So, code should pick two random number from that array, and place it randomly anywhere. for example, it picks [..,7,], and it places it randomly in front of [..3], so array should now be; [1,2,7,3,4,5,6,8]... then it picks [,5] and randomly insert it in first index [5,1,2,7,3,4,5,6,8]... THIS IS SEMI SORTED..
PROBLEM - I do not understand how to move it in front of random element. All my code does is swaps the elements, so we get [1,2,7,4,5,6,3,8] after first iteration. I do not want to swap. I need help moving random numbers picked up in array moving randomly.
Problem lies in the code below, this is wrong implementation;
MY code implementation (part of it), can someone correct me
Arrays.sort(array); // Sort the array.
System.out.println("Original sorted:" + Arrays.toString(array));
for(j=0; j<numElementsChange; j++)
{
int temp = random.nextInt(array.length);
int swap = random.nextInt(array.length);
temp = array[swap];
array[swap] = array[j];
array[j] = temp;
}
System.out.println("Pre sorted:" + Arrays.toString(array));