for ( I = 0; I < N; I++ )
for ( J = I+1; J < N; J++ )
if ( A[I] < A[J] )
swap(A,I,J);
ここで, swap(A,I,J) は配列 A の第 I, J 要素
を入れ換える関数である.
def swap(A,I,J) {
T = A[I]; A[I] = A[J]; A[J] = T;
}
for ( I = 0; I < N; I++ )
for ( J = N-1; J > I; J-- ) /* A[I] が終点 */
if ( A[J] > A[J-1] )
swap(A,J,J-1);
/* sort A[B]...A[E] in increasing order */
def qs(A,B,E) {
if ( B >= E ) return; /* nothing to be done */
M = idiv(B+E,2);
Sep = A[M]; /* Sep : separator */
swap(A,B,M); /* put the separator at the top of A */
Last = B;
/* A[B+1],...,A[Last] < Sep, A[Last+1],...,A[I-1] >= Sep */
for ( I = B+1; I <= E; I++ )
if ( A[I] < Sep ) {
Last++;
swap(A,I,Last);
}
/*restore the separator */
swap(A,B,Last);
/* recursion for the two parts */
qs(A,B,Last-1);
qs(A,Last+1,E);
}
再帰のたびに余分なメモリが必要になるが, リストを用いた次のような 分かりやすいプログラムも書ける.
def qs_list(L)
{
if ( L == [] )
return L;
/* use the first element of L as a separator */
/* it is somewhat dangerous (why?) */
Sep = car(L);
L = cdr(L);
/* Left will be the set of elements less than or equal to Sep */
/* Right will be the set of elements greater than Sep */
Left = [];
Right = [];
for ( ; L != []; L = cdr(L) ) {
T = car(L);
if ( T <= Sep )
Left = cons(T,Left);
else
Right = cons(T,Right);
}
/* recursion */
Left = qs_list(Left);
Right = qs_list(Right);
/* Left + [Sep] + Right => sorted list */
return append(Left,cons(Sep,Right));
}