count sort, radix sort, bucket sort

本文介绍了计数排序、基数排序及桶排序等非比较型排序算法,并提供了详细的实现代码与复杂度分析。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

count sort, radix sort, bucket sort

标签(空格分隔): algorithms


基于比较的排序算法,都逃不过 O ( n l o g n ) O(nlogn) O(nlogn)的宿命1。而非基于比较的排序,如计数排序,基数排序,桶排序则无此限制。它们充分利用待排序的数据的某些限定性假设,来避免绝大多数的“比较”操作。

计数排序

http://www.geeksforgeeks.org/counting-sort/

时间复杂度: O ( N + K ) O(N+K) O(N+K),N为元素个数,K为元素最大值。是一种稳定的排序算法。

但是我觉得时间复杂度其实还是 O ( N ) O(N) O(N),因为不管是计数还是最后把每个元素放入正确的位置都是 O ( N ) O(N) O(N)

#include <string>
#include <vector>
#include <iostream>

using namespace std;

/*
O(n+k)
最后count数组相当于往后移了一个元素。
*/

void count_sort(string &s)
{
	const int range = 255;
	vector<int> count(range+1,0);

	for (auto c : s)
		count[c]++;

	for (int i = 1; i <= range; i++)
		count[i] += count[i-1];

	string temp(s.size(), ' ');

	//如果改成从右到左循环,则是稳定的。
	//当然还有一种做法,即不用累加count数组,直接扫描count数组,设置一个全局index,这样会有问题:不稳定。但改成从右到左循环,还是稳定的。
	/*
	for (int i = s.size()-1; i >= 0; i--)
	{
		temp[count[s[i]] = s[i];
		count[s[i]]--;
	}
	*/
	for (auto c : s)
	{
		temp[count[c]-1] = c;
		count[c]--;
	}

	s = temp;

}

int main()
{
	string s = "geeksforgeeks";
	count_sort(s);
	cout << s << endl;
}

基数排序

http://www.geeksforgeeks.org/radix-sort/
http://notepad.yehyeh.net/Content/Algorithm/Sort/Radix/Radix.php

基数排序的底层排序可以用计数排序或者桶排序。

Let there be d d d digits in input integers. Radix Sort takes O ( d ∗ ( n + b ) ) O(d*(n+b)) O(d(n+b)) time where b b b is the base for representing numbers, for example, for decimal system, b b b is 10. What is the value of d d d? If k k k is the maximum possible value, then d d d would be O ( l o g b ( k ) ) O(log_b(k)) O(logb(k)). (比如k=1000,b=10,则d=3)So overall time complexity is O ( ( n + b ) ∗ l o g b ( k ) ) O((n+b) * log_b(k)) O((n+b)logb(k)). Which looks more than the time complexity of comparison based sorting algorithms for a large k k k. Let us first limit k k k. Let k &lt; = n c k &lt;= n^c k<=nc where c c c is a constant. In that case, the complexity becomes O ( n l o g b ( n ) ) O(nlog_b(n)) O(nlogb(n)). But it still doesn’t beat comparison based sorting algorithms.

What if we make value of b b b larger?. What should be the value of b b b
to make the time complexity linear? If we set b b b as n n n, we get the
time complexity as O ( n ) O(n) O(n). In other words, we can sort an array of
integers with range from 1 to n c n^c nc if the numbers are represented in
base n n n (or every digit takes l o g 2 ( n ) log_2(n) log2(n) bits).

上面最后一段说,如果要给 1 1 1~ n c n^c nc之内的以 n n n为基数的数组排序,那么就可以用线性的复杂度完成。

问题:对 [ 0 , n 2 − 1 ] [0,n^2-1] [0,n21] n n n 个整数进行线性时间排序。
方法1是先把整数转换成n进制再排序,这样每个数有两位,范围为[0…n-1],再进行基数排序。http://blog.youkuaiyun.com/mishifangxiangdefeng/article/details/7685839

#include <string>
#include <algorithm>
#include <vector>
#include <iostream>

using namespace std;

void countSort(vector<int>& nums, int exp)
{
	int sz = nums.size();
	vector<int> output(sz, 0);
	vector<int> count(10, 0);
	for (auto n : nums)
		count[(n/exp)%10]++;
	
	//count[i]表示i前面有count[i]个数字。i处填nums[count[i]]
	for (int i = 1; i < 10; i++)
		count[i] += count[i-1];

	//从后面开始放nums,稳定的排序
	for (int i = sz-1; i >= 0; i--)
	{
		output[count[(nums[i]/exp)%10]-1] = nums[i];
		count[(nums[i]/exp)%10]--;
	}
	nums = output;
}

void radix_sort(vector<int>& nums)
{
	int m = *max_element(nums.begin(), nums.end());
	for (int exp = 1; m/exp > 0; exp *= 10)
		countSort(nums, exp);
}

int main()
{
	int arr[] = {170, 45, 75, 90, 802, 24, 2, 66};
	vector<int> test(arr, arr+sizeof(arr)/sizeof(int));
	radix_sort(test);
	for (auto r : test)
		cout << r << " ";
	cout << endl;

}

LSD:从关键字优先级的开始排,循环
MSD:从关键字优先级的开始排,递归

lsd适合于定长的字符串数组排序:

void lsd(vector<string>& sVec)
{
	const int N = 256+1;
	int w = sVec[0].length();
	int sz = sVec.size();
	for (int d = w-1; d >= 0; d--)
	{
		vector<int> count(N, 0);
		vector<string> temp(N, "");
		for (int i = 0; i < sz; i++)
			count[sVec[i][d]+1]++;
		for (int i = 1; i < N; i++)
			count[i] += count[i-1];
		for (int i = 0; i < sz; i++)
		{
			temp[count[sVec[i][d]]] = sVec[i];
			count[sVec[i][d]]++;
		}
		for (int i = 0; i < sz; i++)
			sVec[i] = temp[i];		
	}
}

int main()
{
	//lsd
	string s1[] = {"dab","add","cab","fab","fee","bad","dad","bee","fed","bed","ebb","ace"};
	vector<string> test1(s1, s1+sizeof(s1)/sizeof(string));
	msd(test1);
	for (auto r : test1)
		cout << r << endl;
}

下面是程序中的count计数方法:
vector sVec: aab, bba, baa。
计的是count[sVec[i][d]+1]++;所以计数如下:

| 0 | …… | ‘a’ | ‘b’ | ‘c’ |
|:----?:----?:----?:----?
| 0 | …… | 0 | 1 | 2 |

第一轮排序(即按第一个字符排序)按count数组将string放置到正确的位置:
aab放到[0],‘a’$\rightarrow 1 b b a 放 到 [ 1 ] , ′ b ′ 1 bba放到[1], &#x27;b&#x27; 1bba[1]b\rightarrow 2 b a a 放 到 [ 2 ] , ′ b ′ 2 baa放到[2], &#x27;b&#x27; 2baa[2]b\rightarrow$2

0……‘a’‘b’‘c’
0……132

……然后以这种方法分别对第2个,第3个字符排序。

下面用msd的方法对一个字符串数组进行按字典序排列。

  1. 根据首字母将数组分成R部分,使用counting sort。
  2. 递归地对这R部分使用counting sort。(为了使待排序的字符串的长度不固定,可以统计字符串结束时候的’\0’,并且递归地时候,直接略过该字符串。)
#include <vector>
#include <iostream>
#include <string>

using namespace std;

//lo~hi表示待排序的字符串为sVec[lo, hi-1]。
void msd(vector<string>& sVec, int lo, int hi, int pos)
{
	const int N = 256+1;
	if (hi <= lo+1) return;
	vector<int> count(N, 0);
	vector<string> temp(hi-lo, "");
	int sz = sVec.size();
	//这和一般的count sort计法略有不同。整体往后移了一位
	for (int i = lo; i < hi; i++)
		count[sVec[i][pos]+1]++;

	for (int i = 1; i < N; i++)
		count[i] += count[i-1];
    //这里虽然是从前往后放置,但是仍然是稳定的。因为前面的计数的时候,计的是count[sVec[i][pos]+1],但是旋转的时候,是从count[sVec[i][pos]]开始放的。
	for (int i = lo; i < hi; i++)
	{
		temp[count[sVec[i][pos]]] = sVec[i];
		count[sVec[i][pos]]++; //相当于把count数组往前移了一个元素
	}
	for (int i = lo; i < hi; i++)
		sVec[i] = temp[i-lo];

	for (int i = 1; i < N-1; i++)
		msd(sVec, lo+count[i], lo+count[i+1], pos+1); //count[i]~count[i+1]相当于对索引为i的元素排序。
}

void msd(vector<string>& sVec)
{
	msd(sVec, 0, sVec.size(), 0);
}

int main()
{
	string s[] = {"dabggg","adda","cabeu","fab","fee","bad","dad","bee","fed","bed","ebb","ace"};
	vector<string> test(s, s+sizeof(s)/sizeof(string));
	msd(test);
	for (auto r : test)
		cout << r << endl;
}

桶排序

http://www.geeksforgeeks.org/bucket-sort-2/

#include <vector>
#include <iostream>
#include <algorithm>

using namespace std;

void bucket_sort(vector<double>& nums)
{
	vector<vector<double>> bucket(10, vector<double>(0));
	for (auto num : nums)
		bucket[10*num].push_back(num);
	for (int i = 0; i < 10; i++)
		sort(bucket[i].begin(), bucket[i].end());
	int index = 0;
	//10个桶
	for (int i = 0; i < 10; i++)
	{
		for (int j = 0; j < bucket[i].size(); j++) 
			nums[index++] = bucket[i][j];
	}
}

int main()
{
	double arr[] = {0.897, 0.565, 0.656, 0.1234, 0.665, 0.3434};
	vector<double> test(arr, arr+sizeof(arr)/sizeof(double));
	bucket_sort(test);
	for (auto r : test)
		cout << r << " ";
	cout << endl;
}

对该算法简单分析,如果数据是期望平均分布的,则每个桶中的元素平均个数为N/M。如果对每个桶中的元素排序使用的算法是快速排序,每次排序的时间复杂度为O(N/Mlog(N/M))。则总的时间复杂度为O(N)+O(M)O(N/Mlog(N/M)) = O(N+ Nlog(N/M)) = O(N + NlogN - NlogM)。当M接近于N是,桶排序的时间复杂度就可以近似认为是O(N)的。就是桶越多,时间效率就越高,而桶越多,空间却就越大,由此可见时间和空间是一个矛盾的两个方面1
1:https://www.byvoid.com/blog/sort-radix

平均复杂度为 O ( n ) O(n) O(n):将元素放入桶中 O ( n ) O(n) O(n),收集元素 O ( n ) O(n) O(n),sort平均 O ( n ) O(n) O(n)

#reference
http://segmentfault.com/a/1190000003054515#articleHeader2
http://hxraid.iteye.com/blog/647759(桶排序效率分析)
https://www.cs.princeton.edu/~rs/AlgsDS07/18RadixSort.pdf(princeton radix sort)


  1. http://segmentfault.com/a/1190000002595152 ↩︎ ↩︎ ↩︎ ↩︎

import tkinter as tk from tkinter import ttk, filedialog, messagebox from PIL import Image, ImageTk, ImageSequence import pandas as pd import time import os import random import threading import queue from bubble import Bubble from selection import Selection from insertion import Insertion from shellsort import Shell from cocktailsort import Cocktail from gnomesort import Gnome from combsort import Comb from countingsort import Counting from radixsort import Radix from bucketsort import Bucket from timsort import Tim from heapsort import Heap from quicksort import Quick from mergesort import Merge window = tk.Tk() window.title("排序方法") window.geometry("1200x800+300+100") # 全局变量声明 current_file = "" arr = [] filename = "sort.csv" gif_label = None gif_frames = [] gif_index = 0 gif_speed = 150 gif_after_id = None scroll_after_id = None BATCH_SIZE = 10000 display_queue = queue.Queue() is_displaying = False sorting_thread = None sorting_active = False def load_gif(file_path, size=(400, 300)): # 加载gif global gif_frames, gif_index # 声明全局变量 gif_frames = [] try: img = Image.open(file_path) for frame in ImageSequence.Iterator(img): resized = frame.copy().resize(size, Image.Resampling.LANCZOS) gif_frames.append(ImageTk.PhotoImage(resized)) gif_index = 0 return bool(gif_frames) except Exception as e: print(f"加载 GIF 出错: {e}") return False def animate_gif(): # 循环显示gif的每一帧 global gif_index, gif_after_id if gif_frames: gif_label.config(image=gif_frames[gif_index]) gif_index = (gif_index + 1) % len(gif_frames) gif_after_id = window.after(gif_speed, animate_gif) def update_gif(file_path): global gif_after_id, gif_frames, gif_index if gif_after_id: window.after_cancel(gif_after_id) if load_gif(file_path, size=(500, 300)): animate_gif() else: gif_label.config(text=f"GIF 加载失败: {file_path}") def load_file(): file_path = filedialog.askopenfilename( title="选择数据文件", filetypes=[("CSV文件", "*.csv"), ("文本文件", "*.txt"), ("所有文件", "*.*")] ) if file_path: status_label.config(text=f"正在加载文件: {os.path.basename(file_path)}...") window.update() threading.Thread(target=load_data_thread, args=(file_path), daemon=True).start() def load_data_thread(file_path): global arr, current_file # 声明全局变量 try: # 分块读取大文件 chunks = [] total_size = os.path.getsize(file_path) processed = 0 for chunk in pd.read_csv(file_path, chunksize=10000): chunks.append(chunk) processed += chunk.memory_usage(index=True, deep=True).sum() progress_value = min(processed / total_size * 100, 100) window.after(0, update_progress, progress_value, f"加载中: {progress_value:.1f}% ({processed / 1e6:.2f}MB/{total_size / 1e6:.2f}MB)") df = pd.concat(chunks) arr = df.values.flatten().tolist() current_file = os.path.basename(file_path) # 更新UI window.after(0, update_treeview_batch, unsort_tree, arr) window.after(0, update_treeview, sort_tree, []) window.after(0, lambda: status_label.config( text=f"已加载: {len(arr)} 条数据 | 文件: {current_file}")) window.after(0, lambda: progress.configure(value=0)) except Exception as e: window.after(0, lambda: messagebox.showerror("错误", f"加载文件失败: {str(e)}")) window.after(0, lambda: status_label.config(text=f"加载失败: {str(e)}")) def update_treeview(treeview, data): treeview.delete(*treeview.get_children()) for value in data: treeview.insert("", "end", values=(value,)) def update_treeview_batch(treeview, data): """分批更新Treeview控件""" treeview.delete(*treeview.get_children()) total = len(data) def add_batch(start_idx=0): end_idx = min(start_idx + BATCH_SIZE, total) for i in range(start_idx, end_idx): treeview.insert("", "end", values=(data[i],)) # 更新进度 progress_value = end_idx / total * 100 window.after(0, lambda: progress.configure(value=progress_value)) if end_idx < total: # 使用计时器安排下一批处理 treeview.after(1, add_batch, end_idx) else: treeview.yview_moveto(1.0) add_batch(0) def scroll_sorted_data(treeview, data): """分批滚动显示排序结果""" global scroll_after_id if scroll_after_id: window.after_cancel(scroll_after_id) treeview.delete(*treeview.get_children()) total = len(data) progress.configure(value=0) def scroll(index=0): # 一次插入一批数据 batch_size = min(BATCH_SIZE, total - index) for i in range(index, index + batch_size): treeview.insert("", "end", values=(data[i],)) # 滚动到底部 treeview.yview_moveto(1.0) # 更新进度 progress_value = (index + batch_size) / total * 100 window.after(0, lambda: progress.configure(value=progress_value)) if index + batch_size < total: # 使用计时器安排下一批显示 scroll_after_id = treeview.after(1, scroll, index + batch_size) else: scroll_after_id = None scroll(0) def generate_random_data(): global arr try: count = int(entry.get()) if count < 100: messagebox.showerror("错误", "请输入100以上的数字") return # 清空现有数组 arr = [] # 更新状态 status_label.config(text=f"正在生成 {count} 条随机数据...") window.update() # 启动线程生成数据 threading.Thread(target=generate_data_thread, args=(count,), daemon=True).start() except ValueError: messagebox.showerror("错误", "请输入有效的数字") def generate_data_thread(count): global arr, current_file, stop_sorting arr = [] # 确保数组为空 stop_sorting = False # 分批生成数据 for i in range(0, count, BATCH_SIZE): batch_size = min(BATCH_SIZE, count - len(arr)) batch = [] for _ in range(batch_size): rand_type = random.choice(["int", "float"]) # 控制整数和浮点数的比例 if len(arr) < count * 0.7: # 70% 整数 batch.append(random.randint(-100000, 100000)) else: batch.append(round(random.uniform(-100000, 100000), 3)) arr.extend(batch) # 更新进度 progress_value = len(arr) / count * 100 window.after(0, lambda: update_progress(progress_value, f"生成进度: {progress_value:.1f}% ({len(arr)}/{count})")) # 保存数据 current_file = "random_data.csv" pd.DataFrame(arr).to_csv(current_file, index=False) # 更新UI window.after(0, lambda: update_treeview_batch(unsort_tree, arr)) window.after(0, lambda: update_treeview(sort_tree, [])) window.after(0, lambda: status_label.config( text=f"已生成 {len(arr)} 条随机数据并保存")) window.after(0, lambda: progress.configure(value=0)) def start_sorting(): global sorting_active # 声明全局变量 if not arr: messagebox.showwarning("警告", "没有数据可排序") return if sorting_active: messagebox.showwarning("警告", "排序正在进行中") return # 更新状态 sorting_active = True algorithm = var.get() algorithm_name = { "bubblesort": "冒泡排序", "selectionsort": "选择排序", "insertionsort": "插入排序", "quicksort": "快速排序", "mergesort": "归并排序", "shellsort": "希尔排序", "cocktailsort": "鸡尾酒排序", "gnomesort": "侏儒排序", "combsort": "梳排序", "countingsort": "计数排序", "radixsort": "基数排序", "bucketsort": "桶排序", "timsort": "Tim排序", "heapsort": "堆排序" }.get(algorithm, algorithm) time_label.config(text="排序耗时: 计算中...") steps_label.config(text="运算步数: 计算中...") result_label.config(text="结果文件: 处理中...") status_label.config(text=f"正在使用 {algorithm_name} 排序数据...") progress.configure(value=0) window.update() # 创建新线程运行排序算法 sorting_thread = threading.Thread(target=choose, daemon=True) sorting_thread.start() def choose(): global sorting_active # 声明全局变量 arr_copy = arr.copy() start_time = time.time() algorithm = var.get() sorted_arr, steps = None, 0 title = "" try: if algorithm == "bubblesort": sorter = Bubble() sorted_arr, steps = sorter.sort(arr_copy) title = "冒泡排序" elif algorithm == "selectionsort": sorter = Selection() sorted_arr, steps = sorter.sort(arr_copy) title = "选择排序" elif algorithm == "insertionsort": sorter = Insertion() sorted_arr, steps = sorter.sort(arr_copy) title = "插入排序" elif algorithm == "quicksort": sorter = Quick() sorted_arr, steps = sorter.sort(arr_copy) title = "快速排序" elif algorithm == "mergesort": sorter = Merge() sorted_arr, steps = sorter.sort(arr_copy) title = "归并排序" elif algorithm == "shellsort": sorter = Shell() sorted_arr, steps = sorter.sort(arr_copy) title = "希尔排序" elif algorithm == "cocktailsort": sorter = Cocktail() sorted_arr, steps = sorter.sort(arr_copy) title = "鸡尾酒排序" elif algorithm == "gnomesort": sorter = Gnome() sorted_arr, steps = sorter.sort(arr_copy) title = "侏儒排序" elif algorithm == "combsort": sorter = Comb() sorted_arr, steps = sorter.sort(arr_copy) title = "梳排序" elif algorithm == "countingsort": sorter = Counting() sorted_arr, steps = sorter.sort(arr_copy) title = "计数排序" elif algorithm == "radixsort": sorter = Radix() sorted_arr, steps = sorter.sort(arr_copy) title = "基数排序" elif algorithm == "bucketsort": sorter = Bucket() sorted_arr, steps = sorter.sort(arr_copy) title = "桶排序" elif algorithm == "timsort": sorter = Tim() sorted_arr, steps = sorter.sort(arr_copy) title = "Tim排序" elif algorithm == "heapsort": sorter = Heap() sorted_arr, steps = sorter.sort(arr_copy) title = "堆排序" else: sorter = Bubble() sorted_arr, steps = sorter.sort(arr_copy) title = "冒泡排序" elapsed_time = time.time() - start_time # 保存结果 with open(filename, "a", encoding="utf-8") as f: # 使用"w"模式覆盖旧文件 f.write(f"\n{title}\n") f.write("\n".join(map(str, sorted_arr))) # 更新UI window.after(0, lambda: scroll_sorted_data(sort_tree, sorted_arr)) window.after(0, lambda: time_label.config( text=f"排序耗时: {elapsed_time:.4f} 秒")) window.after(0, lambda: steps_label.config( text=f"运算步数: {steps}")) window.after(0, lambda: result_label.config( text=f"结果文件: {os.path.abspath(filename)}")) window.after(0, lambda: status_label.config( text=f"{title} 完成! 已处理 {len(arr)} 条数据")) except Exception as e: window.after(0, lambda: messagebox.showerror("排序错误", f"排序过程中出错: {str(e)}")) window.after(0, lambda: status_label.config( text=f"排序失败: {str(e)}")) finally: sorting_active = False progress.configure(value=100) def stop_processing(): stop_sorting = True status_label.config(text="正在停止当前操作...") def on_combobox_select(event=None): algorithm = var.get() gif_map = { "bubblesort": "bubble.gif", "selectionsort": "sele.gif", "insertionsort": "inster.gif", "quicksort": "quick.gif", "mergesort": "merge.gif", "shellsort":"shell.gif", "cocktailsort": "cocktail.gif", "gnomesort": "gnome.gif", "combsort": "comb.gif", "countingsort": "counting.gif", "radixsort": "radix.gif", "bucketsort": "bucket.gif", "timsort": "tim.gif", "heapsort": "heap.gif" } gif_path = gif_map.get(algorithm, "sorting.gif") update_gif(gif_path) # 重置排序结果显示 update_treeview(sort_tree, []) time_label.config(text="排序耗时: --") steps_label.config(text="运算步数: --") result_label.config(text="结果文件: --") def open_file(): file_path = os.path.abspath(filename) if os.path.exists(file_path): os.startfile(file_path) # Windows else: messagebox.showinfo("信息", "结果文件尚未生成") def reset(): global stop_sorting, arr, current_file # 声明全局变量 stop_sorting = True update_treeview(sort_tree, []) time_label.config(text="排序耗时: --") steps_label.config(text="运算步数: --") result_label.config(text="结果文件: --") progress.configure(value=0) status_label.config(text="已重置应用程序") def update_progress(value, text): progress.configure(value=value) status_label.config(text=text) # 创建UI组件 optuple = ("bubblesort", "selectionsort", "insertionsort", "shellsort", "cocktailsort", "gnomesort", "combsort", "countingsort", "radixsort","bucketsort","timsort","heapsort","quicksort","mergesort") var = tk.StringVar(value=optuple[0]) control_frame = ttk.Frame(window) control_frame.pack(fill=tk.X, padx=10, pady=10) ttk.Label(control_frame, text="选择排序算法:").grid(row=0, column=0, padx=5, pady=5) cb = ttk.Combobox(control_frame, textvariable=var, values=optuple, state="readonly", width=15) cb.grid(row=0, column=1, padx=5, pady=5) cb.bind("<<ComboboxSelected>>", on_combobox_select) ttk.Label(control_frame, text="生成数据量:").grid(row=0, column=2, padx=5, pady=5) entry = ttk.Entry(control_frame, width=10) entry.grid(row=0, column=3, padx=5, pady=5) ttk.Button(control_frame, text="生成随机数据", command=generate_random_data).grid(row=0, column=4, padx=5, pady=5) ttk.Button(control_frame, text="选择数据文件", command=load_file).grid(row=0, column=5, padx=5, pady=5) ttk.Button(control_frame, text="开始排序", command=start_sorting).grid(row=0, column=6, padx=5, pady=5) ttk.Button(control_frame, text="停止排序").grid(row=0, column=7, padx=5, pady=5) # 数据展示区域 data_frame = ttk.Frame(window) data_frame.pack(fill="both", expand=True, padx=10, pady=5) # 未排序数据 unsort_frame = ttk.LabelFrame(data_frame, text="未排序数据") unsort_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=True, padx=5, pady=5) unsort_tree = ttk.Treeview(unsort_frame, columns=("value",), show="headings", height=15) unsort_tree.heading("value", text="数值") unsort_tree.column("value", width=100) unsort_tree.pack(side=tk.LEFT, fill=tk.BOTH, expand=True) unsort_scrollbar = ttk.Scrollbar(unsort_frame, orient=tk.VERTICAL, command=unsort_tree.yview) unsort_scrollbar.pack(side=tk.RIGHT, fill=tk.Y) unsort_tree.configure(yscrollcommand=unsort_scrollbar.set) # 排序后数据 sort_frame = ttk.LabelFrame(data_frame, text="排序后数据") sort_frame.pack(side=tk.RIGHT, fill=tk.BOTH, expand=True, padx=5, pady=5) sort_tree = ttk.Treeview(sort_frame, columns=("value",), show="headings", height=15) sort_tree.heading("value", text="数值") sort_tree.column("value", width=100) sort_tree.pack(side=tk.LEFT, fill=tk.BOTH, expand=True) # 添加pack sort_scrollbar = ttk.Scrollbar(sort_frame, orient=tk.VERTICAL, command=sort_tree.yview) sort_scrollbar.pack(side=tk.RIGHT, fill=tk.Y) sort_tree.configure(yscrollcommand=sort_scrollbar.set) gif_frame = ttk.Frame(window) gif_frame.pack(fill=tk.X, padx=10, pady=5) gif_label = ttk.Label(gif_frame) gif_label.pack() # 状态信息 status_frame = ttk.Frame(window) status_frame.pack(fill=tk.X, padx=10, pady=5) time_label = ttk.Label(status_frame, text="排序耗时: --") time_label.grid(row=0, column=0, padx=10, pady=5, sticky="w") steps_label = ttk.Label(status_frame, text="运算步数: --") steps_label.grid(row=0, column=1, padx=10, pady=5, sticky="w") result_label = ttk.Label(status_frame, text="结果文件: --") result_label.grid(row=0, column=2, padx=10, pady=5, sticky="w") progress = ttk.Progressbar(status_frame, orient=tk.HORIZONTAL, length=200, mode='determinate') progress.grid(row=0, column=3, padx=10, pady=5) status_label = ttk.Label(status_frame, text="就绪", foreground="blue") status_label.grid(row=0, column=4, padx=10, pady=5, sticky="ew") # 操作按钮 button_frame = ttk.Frame(window) button_frame.pack(fill=tk.X, padx=10, pady=10) ttk.Button(button_frame, text="查看结果文件", command=open_file).pack(side=tk.RIGHT, padx=5) ttk.Button(button_frame, text="重置", command=reset).pack(side=tk.RIGHT, padx=5) # 初始加载示例数据 update_gif("bubble.gif") window.mainloop() 在这个ui里添加了停止按钮,帮我定义停止按钮的程式,利用泡泡排序的flog停止
最新发布
06-21
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值