一、基本算法
1、定义:
冒泡排序是比较基础的排序算法之一,其思想是相邻的元素两两比较,较大的数下沉,较小的数冒起来,这样一趟比较下来,最大(小)值就会排列在一端。整个过程如同气泡冒起,因此被称作冒泡排序。
2、特点:
1)冒泡排序是稳定的排序算法,即相同元素的相对位置在排序前后不会改变
2)时间复杂度为O(n^2)
3)是原地排序算法,不需要额外的存储空间
4)最好情况下的时间复杂度为O(n),即待排序数据已经是有序的情况下
3、算法分析:
冒泡排序的步骤是比较固定的:
1)比较相邻的元素。如果第一个比第二个大,就交换他们两个。
2)每趟从第一对相邻元素开始,对每一对相邻元素作同样的工作,直到最后一对。
3)针对所有的元素重复以上的步骤,除了已排序过的元素(每趟排序后的最后一个元素),直到没有任何一对数字需要比较。
#include <stdio.h>
// perform the bubble sort
void bubbleSort(int array[], int size) {
// loop to access each array element
for (int step = 0; step < size - 1; ++step) {
// loop to compare array elements
for (int i = 0; i < size - step - 1; ++i) {
// compare two adjacent elements
// change > to < to sort in descending order
if (array[i] > array[i + 1]) {
// swapping occurs if elements
// are not in the intended order
int temp = array[i];
array[i] = array[i + 1];
array[i + 1] = temp;
}
}
}
}
// print array
void printArray(int array[], int size) {
for (int i = 0; i < size; ++i) {
printf("%d ", array[i]);
}
printf("\n");
}
int main() {
int data[] = { 32, 15, 11, 26, 53, 87, 3, 61 };
// find the array's length
int size = sizeof(data) / sizeof(data[0]);
bubbleSort(data, size);
printf("Sorted Array in Ascending Order:\n");
printArray(data, size);
}