帮我写一份用pyqt5做的显示冒泡排序的代码
时间: 2024-02-13 10:00:10 浏览: 50
冒泡排序法的代码。。
4星 · 用户满意度95%
好的,以下是一个使用PyQt5实现的冒泡排序可视化的代码示例:
```python
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QLabel, QVBoxLayout
from PyQt5.QtGui import QPainter, QPen, QColor, QPixmap
from PyQt5.QtCore import Qt, QThread, pyqtSignal
import random
import time
class SortThread(QThread):
sort_signal = pyqtSignal(list)
def __init__(self, nums):
super().__init__()
self.nums = nums
def run(self):
for i in range(len(self.nums)):
for j in range(len(self.nums)-i-1):
if self.nums[j] > self.nums[j+1]:
self.nums[j], self.nums[j+1] = self.nums[j+1], self.nums[j]
self.sort_signal.emit(self.nums)
class BubbleSort(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle('Bubble Sort')
self.setGeometry(100, 100, 800, 600)
self.nums = [random.randint(10, 500) for _ in range(50)]
self.label = QLabel(self)
self.label.setGeometry(0, 0, 800, 600)
self.button = QPushButton('Start Sort', self)
self.button.setGeometry(350, 550, 100, 30)
self.button.clicked.connect(self.start_sort)
def start_sort(self):
self.button.setEnabled(False)
self.thread = SortThread(self.nums)
self.thread.sort_signal.connect(self.update_nums)
self.thread.finished.connect(self.enable_button)
self.thread.start()
def enable_button(self):
self.button.setEnabled(True)
def update_nums(self, nums):
self.nums = nums
self.label.setPixmap(self.draw_pixmap())
def draw_pixmap(self):
pixmap = QPixmap(800, 600)
pixmap.fill(Qt.white)
painter = QPainter(pixmap)
painter.setPen(QPen(QColor(0, 0, 0), 3, Qt.SolidLine))
for i, num in enumerate(self.nums):
painter.drawLine(50 + i*15, 550, 50 + i*15, 550-num)
painter.end()
return pixmap
if __name__ == '__main__':
app = QApplication(sys.argv)
window = BubbleSort()
window.show()
sys.exit(app.exec_())
```
这个程序会在GUI界面上随机生成50个数,并将其绘制成垂直线段。点击`Start Sort`按钮后,程序会启动一个新线程开始排序,同时在界面上更新显示,直到排序完成。这样就实现了一个简单的冒泡排序可视化程序。
阅读全文