Quick Sort in Java and Erlang

时间:2014-08-29 05:13:37   收藏:0   阅读:251

Quick Sort In Java.

public static void quickSort(int[] a, int p, int r) {
        if (p < r) {
            int q = partition(a, p, r);
            quickSort(a, p, q);
            quickSort(a, q + 1, r);
        }
    }

    private static int partition(int[] a, int p, int r) {

        int x = a[p];
        int i = p - 1;
        int j = r + 1;

        while (true) {
            i++;
            while (i < r && a[i] < x)
                i++;
            j--;
            while (j > p && a[j] > x)
                j--;

            if (i < j)
                swap(a, i, j);
            else
                return j;
        }
    }

    private static void swap(int[] a, int i, int j) {
        int temp = a[i];
        a[i] = a[j];
        a[j] = temp;
    }

Quick Sort in Erlang

%% much easier than Java.
q_sort([]) -> [];
q_sort([Pivot|T]) ->
    q_sort([X || X <- T, X < Pivot ])
    ++ [Pivot] ++
    q_sort([X || X <- T, X >= Pivot]).

For me, Erlang is easier to understand.

extended question:

for given number N, find {A,B,C} which A+B+C<N and A*A + B*B = C*C.

pyth_list(N) ->
    [{A,B,C} ||
     A <- lists:seq(1, N),
     B <- lists:seq(1, N),
     C <- lists:seq(1, N),
     A+B+C =< N,
     A*A + B*B =:= C*C
    ].

For me, Java would need much more code.


评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!