Merge sorting, sorting by dividing a random array in half and then putting them in numeric order. Concept is called "Divide and Conquer." The output is out of order and I don't see anything wrong with this code. Main just outputs all the numbers in the array. FYI, other parts of the code isn't the problem. But if you need it I can give it to you.
private void merge(int[] a, int first, int mid, int last)
{
int size = last - first + 1;
int [] temp = new int[size];
int i = first, j = mid + 1;
for(int s = 0; s < size; s++){ // a.length
if(i > mid){ // case a
temp[s] = a[j];
j++;
}else if(j > last){ // case b
temp[s] = a[i];
i++;
}else if(a[i] < a[j]){ // case c
temp[s] = a[i];
i++;
}else if(a[j] <= a[i]){ // case d
temp[s] = a[j];
j++;
}
}
for(int s = first; s < size; s++){
a[first] = temp[s - first];
}
}
public void mergeSort(int[] a, int first, int last)
{
int size = last - first + 1, mid;
if(size == 1){
steps++;
}else if(size == 2){
if(a[last] > a[first]){
int temp = a[last];
a[last] = a[first];
a[first] = temp;
steps += 3;
}
}else{
mid = (last + first) / 2;
mergeSort(a, first, mid);
mergeSort(a, mid + 1, last);
merge(a, first, mid, last);
steps += 4;
}
}
This is what the generator looks like:
private void fillArray(int numInts, int largestInt)
{
myArray = new int[numInts];
Random randGen = new Random();
for(int loop = 0; loop < myArray.length; loop++){
myArray[loop] = randGen.nextInt(largestInt) + 1;
}
}