1. 程式人生 > >Python快速排序演算法

Python快速排序演算法

# -*- coding: utf-8 -*-
# 快速排序演算法
import random

fenshu = int(input("請輸入考試滿分:"));
renshu = int(input("請輸入考試人數:"));
sortsre = input("倒敘/正序 請選擇 Y/N:");
while sortsre!="Y" and sortsre!="N":
    print("您輸入的引數有誤!");
    sortsre = input("倒敘/正序 請選擇 Y/N:");

classmates = [0]*(renshu);

#模擬資料生成
for num in range(renshu):
    shu = random.randint(0
,fenshu); classmates[num] = shu; print("%d分" % (shu)); print(""); print(""); #重組資料 def fangfa(left,right): if left>right: return; jizhunshu = classmates[left]; i = left; j = right; if sortsre=="N": while i!=j: while (classmates[j]>=jizhunshu) and
(i<j): j-=1; while (classmates[i]<=jizhunshu) and (i<j): i+=1; if i<j: t=classmates[i]; classmates[i]=classmates[j]; classmates[j]=t; elif sortsre=="Y": while i!=j: while
(classmates[j]<=jizhunshu) and (i<j): j-=1; while (classmates[i]>=jizhunshu) and (i<j): i+=1; if i<j: t=classmates[i]; classmates[i]=classmates[j]; classmates[j]=t; classmates[left] = classmates[i]; classmates[i] = jizhunshu; fangfa(left,i-1); fangfa(i+1,right); #遞迴方法 fangfa(0,len(classmates)-1); #列印資料 for num in classmates: print("%d分" % (num));