# Erlang程式設計與問題解決/排序

## 快速排序

```quicksort([]) -> [];
quicksort([X|Xs]) ->
quicksort([Y || Y<-Xs, Y=<X]) ++ [X] ++ quicksort([Z || Z<-Xs, Z>X]).
```

```append([], Ys) -> Ys;
append([X|Xs], Ys) -> [X | append(Xs, Ys)].
```

### 強化快速排序

```append(Xs, Ys) -> append(Xs, [], Ys).

append([], Accumulator, Ys) ->
lists:reverse(Accumulator) ++ Ys;
append([X|Xs], Accumulator, Ys) ->
append(Xs, [X|Accumulator], Ys).
```

```quicksort([]) -> [];
quicksort([X|Xs]) ->
append(
quicksort([Y || Y<-Xs, Y=<X]),
[X | quicksort([Z || Z<-Xs, Z>X]) ]
).
```

## 氣泡排序

```compare([X,Y|Ys]) when X > Y ->
[Y|compare([X|Ys])];
compare([X,Y|Ys]) ->
[X|compare([Y|Ys])];
compare(Xs) ->
Xs.
```

```bubblesort(Xs) ->
compare(length(Xs)-1, Xs).

compare(N, Xs) when N > 0 ->
Rs = compare(Xs),
compare(N-1, Xs);
compare(_, Xs) ->
Xs.
```

bubblesort/1 是主程式， compare/2 決定要掃瞄幾次， compare/1 進行一次掃瞄並拋回結果。

compare/1 在此決定了氣泡排序的主要運作邏輯，而且，也可以藉由改寫這個函數，使排序變成選擇排序

### 選擇排序

```select([X|Xs]) ->
case select(Xs) of
[] ->
[X];
[Y|Ys] ->
if
X > Y ->
[Y,X|Ys];
true ->
[X,Y|Ys]
end
end;
select([]) ->
[].
```

```compare(N, Xs) when N > 0 ->
Rs = select(Xs),
compare(N-1, Xs);
compare(_, Xs) ->
Xs.
```

## 插入排序

```insert(X, []) ->
[X];
insert(X, [Y|Ys]) when X > Y ->
[ Y | insert(X, Ys) ];
insert(X, [Y|Ys]) ->
[X,Y|Ys].
```

```insertionsort(Xs) ->
insert_pile(Xs, []).
```

insert_pile/2 的二個參數，第一個是原數列，第二個是已排序數列。 insert_pile/2 定義為

```insert_pile([], Ys) ->
Ys;
insert_pile([X|Xs], Ys) ->
Rs = insert(X, Ys),
insert_pile(Xs, Rs).
```