java - Having an issue with method function -
so basic overall function of code take in the array , sort in ascending order. no errors within code believe wrong. have made test cases , have failed , have feeling in recursivesort
method doing wrong. have done multiple debugging walk through , cant find problem?
public class recursivesorter { private int[] sortedarray; private int[] array; public recursivesorter() { array = new int[1]; } public recursivesorter(int[] a) { array = a; } public void setarray(int[] a) { array = a; } public int[] getsortedarray() { return sortedarray; } public int[] getoriginalarray() { return array; } public int[] sort() { sortedarray = array; recursivesort(sortedarray.length - 1); return sortedarray; } public int[] recursivesort(int endindex) { if (endindex >= 0) { int m = getmaxindex(endindex, sortedarray); swap(m, endindex, sortedarray); recursivesort(endindex-1); } return sortedarray; } public int getmaxindex(int endindex, int[] a) { int max = a[0]; int maxindex = 0; (int = 1; < endindex; i++) { if (a[i] > max) { max = a[i]; maxindex = i; } } return maxindex; } public void swap(int src, int dest, int[] a) { int temp = a[dest]; a[dest] = src; a[src] = temp; } public string tostring() { return "original: " + prettyprint(getoriginalarray()) + "\n" + "sorted: " + prettyprint(getsortedarray()); } private string prettyprint(int[] a) { string s = ""; (int : a) s += + " "; return s; } public static void main(string[] args) { // automate running, not testing int[] array = {5, 67, 12, 20}; recursivesorter s = new recursivesorter(array); s.sort(); system.out.println(s); // uses sorter.tostring } }
swap method has error:
a[dest] = src;
should be:
a[dest] = a[src];
also line not copy array, have array
, sortedarray
referencing same array object.
sortedarray = array;
replace with:
sortedarray = arrays.copyof(array, array.length);
also in method getmaxindex
missing equals sign:
for (int = 1; < endindex; i++) {
should be:
for (int = 1; <= endindex; i++) {
Comments
Post a Comment