Question by
Michael074 · May 11, 2017 at 02:14 PM ·
sorting
help please. I wrote a mergesort algorithm that does nothing.
public class mb_Mergesort : MonoBehaviour {
public int[] numbers = new int[7] {1,2,4,4,3,1,2};
void Start () {
for (int i = 0; i < numbers.Length; i++) {
Instantiate (new Tile (numbers [i]).image, new Vector3 (i, 0, -1), Quaternion.identity);
}
Mergesort (numbers, 0, numbers.Length - 1);
for (int i = 0; i < numbers.Length; i++) {
Instantiate (new Tile (numbers [i]).image, new Vector3 (i, 2, -1), Quaternion.identity);
}
}
void Mergesort(int[] input, int startIndex, int endIndex){
int splitIndex;
if (startIndex < endIndex) {
splitIndex = (startIndex + endIndex) / 2;
Mergesort (input, startIndex, splitIndex);
Mergesort (input, splitIndex + 1, endIndex);
Merge (input, startIndex, splitIndex, endIndex);
}
}
void Merge(int [] input, int startIndex, int splitIndex, int endIndex){
int[] duplicate = new int[input.Length];
int leftPointer = startIndex;
int rightPointer = splitIndex + 1;
int duplicatePointer = startIndex;
while (duplicatePointer <= endIndex) {
if (leftPointer > splitIndex || rightPointer < leftPointer) {
duplicate [duplicatePointer++] = input [rightPointer++];
} else {
duplicate [duplicatePointer++] = input [leftPointer++];
}
}
duplicatePointer = startIndex;
for (int i = startIndex; i < endIndex + 1; i++) {
input [i] = duplicate [i];
}
}
}
when i run the code it just prints the original array twice. I'm running it through Unity which is why I have instantiate statements. I'm making an image of the number on the screen..
Comment