Internal Sorting: Bubble sort: Sorting by Exchanging

Bubble sort:冒泡排序


Animation

这里写图片描述
Static visualization of bubble sort


这里写图片描述
An example of bubble sort. Starting from the beginning of the list, compare every adjacent pair, swap their position if they are not in the right order (the latter one is smaller than the former one). After each iteration, one less element (the last one) is needed to be compared until there are no more elements left to be compared.


这里写图片描述
A bubble sort, a sorting algorithm that continuously steps through a list, swapping items until they appear in the correct order. The list was plotted in a Cartesian coordinate system, with each point (x,y) indicating that the value y is stored at index x. Then the list would be sorted by bubble sort according to every pixel’s value. Note that the largest end gets sorted first, with smaller elements taking longer to move to their correct positions.


Complexity

ClassSorting algorithm
Data structureArray
Worst case performance O(n2)
Best case performance O(n)
Average case performance O(n2)
Worst case space complexity O(1) auxiliary

Algorithm B

Algorithm B (Bubble sort). Records R1,...,RN are rearranged in place; after
sorting is complete their keys will be in order, K1<=...<=KN .
B1. [Initialize BOUND .] Set BOUNDN . ( BOUND is the highest index for which
the record is not known to be in its final position; thus we are indicating
that nothing is known at this point.)
B2. [Loop on j .] Set t0. Perform step B3 for j=1,2,...,BOUND1 , and
then go to step B4. (If BOUND=1 , this means go directly to B4.)
B3. [Compare/exchange Rj:Rj+1 .] If Kj>Kj+1 , interchange RjRj+1 and
set tj .
B4. [Any exchanges?] If t=0 , terminate the algorithm. Otherwise set BOUNDt
and return to step B2. |


Flow diagram

Bubble sort:Sorting by Exchanging:Internal Sorting


Data table


Java program

In this program, R1,…,RN were simplified to K1,…,KN.

/**
 * Created with IntelliJ IDEA.
 * User: 1O1O
 * Date: 11/26/13
 * Time: 10:01 PM
 * :)~
 * Bubble sort:Sorting by Exchanging:Internal Sorting
 */
public class Main {

    public static void main(String[] args) {
        int N = 16;
        int[] K = new int[17];
        int temp;

        /*Prepare the data*/
        K[1] = 503;
        K[2] = 87;
        K[3] = 512;
        K[4] = 61;
        K[5] = 908;
        K[6] = 170;
        K[7] = 897;
        K[8] = 275;
        K[9] = 653;
        K[10] = 426;
        K[11] = 154;
        K[12] = 509;
        K[13] = 612;
        K[14] = 677;
        K[15] = 765;
        K[16] = 703;

        /*Output unsorted Ks*/
        System.out.println("Unsorted Ks:");
        for(int i=1; i<=N; i++){
            System.out.println(i+":"+K[i]);
        }
        System.out.println();

        /*Kernel of the Algorithm!*/
        for(int BOUND=N; BOUND>1; BOUND--){
            for(int j=1; j<= BOUND-1; j++){
                if(K[j] > K[j+1]){
                    temp = K[j];
                    K[j] = K[j+1];
                    K[j+1] = temp;
                }
            }
        }

        /*Output sorted Ks*/
        System.out.println("Sorted Ks:");
        for(int i=1; i<=N; i++){
            System.out.println(i+":"+K[i]);
        }
    }
}

Outputs

Unsorted Ks:
1:503
2:87
3:512
4:61
5:908
6:170
7:897
8:275
9:653
10:426
11:154
12:509
13:612
14:677
15:765
16:703

Sorted Ks:
1:61
2:87
3:154
4:170
5:275
6:426
7:503
8:509
9:512
10:612
11:653
12:677
13:703
14:765
15:897
16:908

Reference

<< The art of computer programming: Sorting and Searching >> VOLUME 3, DONALD E. KNUTH
https://en.wikipedia.org/wiki/Bubble_sort

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我将用Python实现三个排序算法:冒泡排序,快速排序和堆排序,并绘制一张图表展示不同大小的输入数组下这些排序算法的运行时间。 以下是实现这三个算法的Python代码: ```python import random import time # 冒泡排序 def bubble_sort(arr): n = len(arr) for i in range(n): for j in range(n-i-1): if arr[j] > arr[j+1]: arr[j], arr[j+1] = arr[j+1], arr[j] # 快速排序 def quick_sort(arr): if len(arr) <= 1: return arr else: pivot = arr[0] left = [x for x in arr[1:] if x < pivot] right = [x for x in arr[1:] if x >= pivot] return quick_sort(left) + [pivot] + quick_sort(right) # 堆排序 def heapify(arr, n, i): largest = i l = 2 * i + 1 r = 2 * i + 2 if l < n and arr[largest] < arr[l]: largest = l if r < n and arr[largest] < arr[r]: largest = r if largest != i: arr[i], arr[largest] = arr[largest], arr[i] heapify(arr, n, largest) def heap_sort(arr): n = len(arr) for i in range(n//2 - 1, -1, -1): heapify(arr, n, i) for i in range(n-1, 0, -1): arr[i], arr[0] = arr[0], arr[i] heapify(arr, i, 0) # 测试排序算法的运行时间 def test_sorting_algorithm(algorithm, arr): start_time = time.time() algorithm(arr) end_time = time.time() return end_time - start_time # 绘制排序算法的运行时间图表 def plot_running_time(): sizes = [100, 500, 1000, 5000, 10000, 50000, 100000] bubble_sort_times = [] quick_sort_times = [] heap_sort_times = [] for size in sizes: arr = [random.randint(0, 1000) for _ in range(size)] bubble_sort_times.append(test_sorting_algorithm(bubble_sort, arr)) quick_sort_times.append(test_sorting_algorithm(quick_sort, arr)) heap_sort_times.append(test_sorting_algorithm(heap_sort, arr)) import matplotlib.pyplot as plt plt.plot(sizes, bubble_sort_times, label='Bubble Sort') plt.plot(sizes, quick_sort_times, label='Quick Sort') plt.plot(sizes, heap_sort_times, label='Heap Sort') plt.xlabel('Input size') plt.ylabel('Running time (seconds)') plt.title('Running time of sorting algorithms') plt.legend() plt.show() plot_running_time() ``` 上面的代码中,我们使用了Python的标准库`random`来生成随机数数组。`test_sorting_algorithm`函数用来测试给定排序算法在给定数组上的运行时间。`plot_running_time`函数则用来绘制排序算法的运行时间图表,它调用
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值