java quicksort help?
// The "MyQuickSort" class. //S import java.awt.*; import java.util.*; import java.lang.*; import java.io.*; public class Quicksort { /** * @param args */ static int arraylength; public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader (new FileReader ("list_to_sort.txt")); PrintWriter out = new PrintWriter (new FileWriter ("sorted.txt")); int temp; arraylength = Integer.parseInt (in.readLine ()); int[] sort = new int [arraylength]; for (int i = 0 ; i < arraylength ; i++) { sort [i] = Integer.parseInt (in.readLine ()); } sort=quicksort(sort,0,arraylength-1); for (int i = 0 ; i < arraylength ; i++) { out.println (sort [i]); System.out.println(sort [i]); } in.close (); out.close (); } public static int[] quicksort(int [] array, int beg,int end ) { if (beg < end) { int pivotindex=(int)(Math.random()*end)+beg; int pivotNewIndex = partition(beg, end,array, pivotindex); // Recursively sort elements smaller than the pivot quicksort(array,beg , pivotNewIndex - 1); // Recursively sort elements at least as big as the pivot quicksort(array, pivotNewIndex + 1, end); } return array; } public static int partition(int beg, int end, int [] qsort,int pivotindex) { int pivot=qsort[pivotindex]; int temp; int indexstore; temp=qsort[end]; qsort[end]=qsort[pivotindex]; qsort[pivotindex]=temp; temp=0; indexstore=beg; for (int i=beg; i<end; i++) { if (qsort[i] < pivot) { temp=qsort[indexstore]; qsort[indexstore]=qsort[i]; qsort[i]=temp; } indexstore+=1; qsort[i]=qsort[indexstore]; } temp=qsort[indexstore]; qsort[indexstore]=qsort[end]; qsort[end]=temp; return indexstore; } }
1. You are multiplying Math.random() by the wrong value. (beg might not be 0) 2. When should you update indexstore? 3. Why are you clobbering qsort[i] every time?
thnk u, tht wasnt the problem, but thnk u
Join our real-time social learning platform and learn together with your friends!