java - Quicksort: Almost sorted, but not quite. What's wrong? -
here's code. output correctly sorted array, there several elements out of order. able spot error?
i'm pretty sure swap , quicksort methods correct, i'm posting methods here in case.
package quicksort; import java.util.random; import java.util.arrays; public class quicksort { /** * @param args command line arguments */ private static int[] u; public static void main(string[] args) { u = makearray(100); system.out.println(arrays.tostring(u)); quicksort(0, u.length - 1); system.out.println(arrays.tostring(u)); } public static int[] makearray(int n) { int[] = new int[n]; int j; random r = new random(); (int = 0; < n; i++) { j = (r.nextint(100) + 1); a[i] = j; } return a; } public static int partition(int left, int right, int pivot) { int p = pivot; // pivot int lpt = left - 1; int rpt = right + 1; while (true) { while ((lpt < right) && (u[++lpt] < p)); while ((rpt > left) && (u[--rpt] > p)); if (lpt >= rpt) { break; } else { swap(lpt, rpt); system.out.println("swapping " + lpt + " " + rpt); } } return lpt; } public static void swap (int a, int b) { int temp = u[a]; u[a] = u[b]; u[b] = temp; } public static void quicksort(int l, int r) { if (r - l <= 0) { return; } else { int part = partition(l, r, u[l]); quicksort (l, part - 1); quicksort (part + 1, r); } }
}
the problem in partition method. pivot element not being placed in correct position @ end of swaps. i've changed method signature pass in position of pivot element, rather value of pivot, in quicksort() write:
int part = partition(l, r, l);
in body of pivot method, swapped pivot element end of section (by swapping right). ignore element our swaps, took away "+ 1" on initialisation of rpt. added statement after while loop move pivot element place. 3 changes, method looks this:
public static int partition(int left, int right, int pivotposition) { int p = u[pivotposition]; // pivot // move pivot end swap(pivotposition, right); int lpt = left - 1; int rpt = right; while (true) { while ((lpt < right) && (u[++lpt] < p)); while ((rpt > left) && (u[--rpt] > p)); if (lpt >= rpt) { break; } else { swap(lpt, rpt); system.out.println("swapping " + lpt + " " + rpt); } } // put pivot in place swap(lpt, right); return lpt; }
with these changes, code works me.
Comments
Post a Comment