Basic algorithm - sorting problem

xiaoxiao2021-03-06  104

Fourth, ordering algorithm

1. Quick sort:

Procedure Qsort (L, R: Integer);

Var i, J, MID: Integer;

Begin

I: = L; J: = R; MID: = a [(1) Div 2]; {{Defined the number of the current sequence in the middle position as an intermediate number

}

Repeat

While a [i]

While a [J]> MID DO DO DEC (j); {在 半 半 小 数 数}}}}}

If i <= j Then Begin {If you find a group of sorted targets, exchange them}

SWAP (a [i], a [j]);

INC (i); dec (j); {continuing to find}

END;

Until I> J;

IF L

I

End; {sort}

B. Insert Sort:

Idea: Current a [1] .. a [i-1] has been ranked, now inserting a [i] to make A [1] .. a [i] is orderly.

Procedure insert_sort;

Var i, J: integer;

Begin

For i: = 2 to n Do Begin

a [0]: = a [i];

J: = I-1;

While a [0]

a [j 1]: = a [j];

J: = J-1;

END;

a [j 1]: = a [0];

END;

End; {INSET_SORT}

C. Select Sort:

Procedure sort;

Var i, j, k: integer;

Begin

For i: = 1 to N-1 DO

For j: = i 1 to n DO

IF A [I]> a [J] THEN SWAP (A [i], A [J]);

END;

D. Sprinkle

Procedure bubble_sort;

Var i, j, k: integer;

Begin

For i: = 1 to N-1 DO

For J: = N DOWNTO I 1 DO

IF A [J]

END;

E. Stack Sort:

Procedure Sift (I, M: Integer); {Adjusting the subtree of I root into a pile, M is the total number of nodes}

VAR K: Integer;

Begin

a [0]: = a [i]; k: = 2 * i; {The left child of the node i in the full binary tree is 2 * i, the right child is 2 * i 1}

While K <= m Do Begin

IF (k) and (a [k]

IF a [0]

ELSE K: = M 1;

END;

a [i]: = a [0]; {Put the root in the right position}

END;

Procedure Heapsort;

VAR

J: integer;

Begin

For J: = N DIV 2 DOWNTO 1 Do Sift (J, N);

For j: = n Downto 2 do begin

SWAP (A [1], A [J]);

SIFT (1, j-1);

END;

END;

F. Multiplexing

{A is a sequence list, TMP is auxiliary array}

Procedure Merge (VAR A: LISTTYPE; P, Q, R: Integer);

{Combined subsequences A [p..Q] with A [Q 1 "] is an ordered TMP [Pha]} Var I, J, T: Integer;

TMP: LISTTYPE;

Begin

T: = p; i: = p; j: = q 1; {t is TMP pointer, i, j is a pointer of left and right subsequences, respectively.

While (t <= r) DO Begin

IF (i <= q) {left sequence has the remaining} and ((j> r) or (a [i] <= a [j])) {Meet the left sequence

Element requirements}

Then Begin

TMP [T]: = a [i]; INC (i);

end

Else Begin

TMP [T]: = a [j]; inc (j);

END;

INC;

END;

For i: = p to r do a [i]: = TMP [i];

End; {merge}

Procedure merge_sort (var A: listType; p, r: integer); {merge sorting a [p..r]}

Var q: integer;

Begin

IF P <> r the begin

Q: = (p r-1) DIV 2;

Merge_sort (A, P, Q);

MERGE_SORT (A, Q 1, R);

MERGE (A, P, Q, R);

END;

END;

{main}

Begin

Merge_sort (a, 1, n);

End.

G. Boundary Sort

Thought: For each element, you can sort each bit from low to high.

-


New Post(0)