冒泡排序是一种简单的排序算法,通过重复遍历要排序的列表,比较相邻元素并交换顺序错误的元素。以下是使用Python实现的冒泡排序代码及其单元测试:,,``python,def bubble_sort(arr):, n = len(arr), for i in range(n):, for j in range(0, n-i-1):, if arr[j] > arr[j+1]:, arr[j], arr[j+1] = arr[j+1], arr[j], return arr,,# 单元测试,import unittest,,class TestBubbleSort(unittest.TestCase):, def test_bubble_sort(self):, self.assertEqual(bubble_sort([64, 34, 25, 12, 22, 11, 90]), [11, 12, 22, 25, 34, 64, 90]), self.assertEqual(bubble_sort([]), []), self.assertEqual(bubble_sort([1]), [1]), self.assertEqual(bubble_sort([3, 2, 1]), [1, 2, 3]),,if __name__ == '__main__':, unittest.main(),
``
当然,以下是一段使用冒泡排序算法的C语言代码:,,``c,#include,,void bubbleSort(int arr[], int n) {, int i, j, temp;, for (i = 0; i< n-1; i++) {, for (j = 0; j< n-i-1; j++) {, if (arr[j] > arr[j+1]) {, temp = arr[j];, arr[j] = arr[j+1];, arr[j+1] = temp;, }, }, },},,int main() {, int arr[] = {64, 34, 25, 12, 22, 11, 90};, int n = sizeof(arr)/sizeof(arr[0]);, bubbleSort(arr, n);, printf("Sorted array: \n");, for (int i=0; i< n; i++), printf("%d ", arr[i]);, return 0;,},
``