【PyQt】插入排序算法
# coding=utf-8 import sys from PyQt4.QtGui import * from PyQt4.QtCore import * class MainWindow(QMainWindow): def __init__(self,parent=None): super(MainWindow,self).__init__(parent) self.setWindowTitle(u'算法实现') self.setWindowIcon(QIcon('image/5.png')) #设置输入数据窗口&数据输出窗口 in_out_putDock=QDockWidget() in_out_putDock_workspace=QWorkspace() in_out_putDock.setWidget(in_out_putDock_workspace) label_in=QLabel(u'输入数据窗口,数据以“,”分隔') label_out=QLabel(u'输出数据窗口') self.inTextEdit=QTextEdit() self.outTextEdit=QTextEdit() layout=QGridLayout() layout.addWidget(label_in,0,0) layout.addWidget(self.inTextEdit,1,0,1,4) layout.addWidget(label_out,2,0) layout.addWidget(self.outTextEdit,3,0,1,4) in_out_putDock_workspace.setLayout(layout) self.addDockWidget(Qt.LeftDockWidgetArea,in_out_putDock) #设置算法(algorithm)按钮及运行时间显示控件 algori_Dock=QDockWidget() algori_Dock_workspace=QWorkspace() algori_Dock.setWidget(algori_Dock_workspace) self.clearButton=QPushButton(u'清除输入输出框内容') self.insert_sort_Button=QPushButton(u'插入排序算法') time_label=QLabel(u'算法运行时间: ') self.runTime_label=QLabel() self.runTime_label.setFrameShape(QFrame.Box) layout2=QGridLayout() layout2.addWidget(time_label,0,0) layout2.addWidget(self.runTime_label,0,1) layout2.addWidget(self.clearButton,1,0,1,1) layout2.addWidget(self.insert_sort_Button,2,0,1,2) layout2.setRowStretch(3,1) algori_Dock_workspace.setLayout(layout2) self.addDockWidget(Qt.RightDockWidgetArea,algori_Dock) #将按钮与动作相连 self.connect(self.insert_sort_Button,SIGNAL('clicked()'),self.insertSortUp) self.connect(self.clearButton,SIGNAL('clicked()'),self.clearInOutEdit) #从输入文本框中获取文本并返回数字列表 def getData(self): textData=self.inTextEdit.document() textData_str=textData.toPlainText() data=str(textData_str).split(',') data_f=[] for i in range(len(data)): data_f.append(float(data[i])) return data def showResult(self,pname,runcount,time,data): tex=pname+u': ||运行时间为:'+str(time)+u' 毫秒 ||运行所用循环执行次数为:'+str(runcount)+u' 次||运行结果为: '+str(data) self.outTextEdit.setText(tex) self.runTime_label.setText(str(time)+u'毫秒') def insertSortUp(self): run_time=QTime() run_time.start() data=self.getData() runcount=0 #插入排序算法 j=1 for j in range(len(data)): key=data[j] i=j-1 while i>=0 and data[i]>key: data[i+1]=data[i] i-=1 runcount+=1 data[i+1]=key spend_time=run_time.elapsed() self.showResult(u'插入排序算法',runcount,spend_time,data) def clearInOutEdit(self): self.outTextEdit.clear() self.inTextEdit.clear() app=QApplication(sys.argv) form=MainWindow() form.show() app.exec_()
待添加其他排序算法