0

## 我想寫出 quicksort 和bubble sort的題目,但我寫不出來

(input values) (expected output)

1. ``````  10,20,80,5,90,60,15        5,10,15,20,60,80,90,60
``````
2. ``````  10,30,100,-15,0,90,20      -15,0,10,20,30,90,100
``````
3. ``````  -1,abc,345,90,2,50         error(undefind)
``````

data = [10,30,100,-15,,90,20]

def quicksort(data, left, right):
if left >= right :
return

``````min = left
pig = right
clock = data[left]

while min != pig:
while data[pig] > clock and min < pig:
pig -= 1
while data[min] <= clock and min < pig:
min += 1
if min < pig:
data[min], data[pig] = data[pig], data[min]

data[left] = data[min]
data[min] = clock

quicksort(data, left, min-1)
quicksort(data, min+1, right)
``````

quicksort(data, 0, len(data)-1)
print(data)

froce iT邦大師 1 級 ‧ 2020-12-21 12:52:06 檢舉

https://ithelp.ithome.com.tw/articles/10202330

### 1 個回答

1

iT邦大神 1 級 ‧ 2020-12-21 17:42:02

``````data = [89, 34, 23, 78, 67, 100, 66, 29, 79, 55, 78, 88, 92, 96, 96, 23]

def quicksort(data, left, right): # 輸入資料，和從兩邊開始的位置
if left >= right :            # 如果左邊大於右邊，就跳出function
return

i = left                      # 左邊的代理人
j = right                     # 右邊的代理人
key = data[left]                 # 基準點

while i != j:
while data[j] > key and i < j:   # 從右邊開始找，找比基準點小的值
j -= 1
while data[i] <= key and i < j:  # 從左邊開始找，找比基準點大的值
i += 1
if i < j:                        # 當左右代理人沒有相遇時，互換值
data[i], data[j] = data[j], data[i]

# 將基準點歸換至代理人相遇點
data[left] = data[i]
data[i] = key

quicksort(data, left, i-1)   # 繼續處理較小部分的子循環
quicksort(data, i+1, right)  # 繼續處理較大部分的子循環

quicksort(data, 0, len(data)-1)
print(data)
``````