Qiuck Sort

Quick Sort is a divide and conquer algorithm.

 

erlang code:

%implements the partition method. Just for demonstration. Actually you can use BIF lists:partition(Cmp, List). part([], _, Smaller, Larger) -> {Smaller, Larger}; part([H|L], Pivot, Smaller, Larger) -> if H < Pivot -> part(L, Pivot, [H | Smaller], Larger); true -> part(L, Pivot, Smaller, [H | Larger]) end. qsort([]) -> []; qsort([H|L]) -> {L1, L2} = part(L, H, [], []), // actually you can use BIF lists:partition(Cmp, List). qsort(L1) ++ [H] ++ qsort(L2).

 

java code:

 

/*If you like Generic Type, you can use <T extends Comparable<? super T>> in below function. I don't like Generic Type that is not simple or graceful. */ public static <T extends Comparable<T>> void sort (T[] list, int begin, int end){ if (begin >= end){ return; } int fence = partition(list, begin, end); sort(list, begin, fence - 1); sort(list, fence + 1, end); } private static <T extends Comparable<T>> int partition(T[] list, int begin, int end){ if(begin >= end){ return begin; } T pivot = list[begin]; int i, j; i = begin; j = end; while(j > i){ while(j > i && list[j].compareTo(pivot)>0){ j--; } if (j > i){ list[i++] = list[j]; } while(j > i && list[i].compareTo(pivot) <= 0){ i++; } if(j > i){ list[j--] = list[i]; } } list[i] = pivot; return i; }

 

 

 

 

你可能感兴趣的:(java,list,PIVOT)