Problems with Quicksort in Java -


so have been testing different sorting algorithms, , have written quicksort! sort of works, sorting bit off! output this:

[0, 1, 2, 3, 8, 6, 5, 4, 7, 9, 20, 16, 22, 21, 14, 17, 18, 10, 15, 19, 13, 11, 23, 12, 26, 24, 25, ... 

this first 27 elements out of 100 sorting. how fill randomized list:

for(int =0; < 100; ++){             int nr = rand.nextint(100);             if (!numbers.contains(new integer(nr))){                 numbers.add(nr);             }else {                 i--;             } }  

here code quicksort:

public class quicksort{ @suppresswarnings("unchecked") static public <t> arraylist<t> sortting(arraylist<t> t){     //system.out.print("-");     t piv;     arraylist<t> left ,right ,newt;     left    = new arraylist<t>();     right   = new arraylist<t>();     newt    = new arraylist<t>();      if (!t.isempty()){         piv = t.get(t.size()/2);         (int =0; < t.size(); i++){             if (0 < ((comparable<t>) piv).compareto(t.get(i))){ //left                 left.add(t.get(i));             }else{  //right                 right.add(t.get(i));             }         }          if (left.isempty() || right.isempty()){             newt.addall(left);             newt.addall(right);             return newt;         }else {             right = sortting(right);             left = sortting(left);              newt.addall(left);             newt.addall(right);         }          return newt;     }     return null;  }  } 

your problem block:

    if (left.isempty() || right.isempty()){         newt.addall(left);         newt.addall(right);         return newt;     } 

if choose pivot @ point happens smallest in current sublist, sublist automatically considered sorted. should remove check , sort left , right sublists.

this okay because you'll go recursive call empty list, in case return null.

if (!t.isempty()){ ... return newt;} return null; 

i'm not sure if arraylist.addall() handles null inputs gracefully. if you're concerned that, can return empty arraylist instead of null.


Comments

Popular posts from this blog

php - Calling a template part from a post -

Firefox SVG shape not printing when it has stroke -

How to mention the localhost in android -