冒泡排序算法C语言实现

来源:互联网 发布:郁冬 it 编辑:程序博客网 时间:2024/05/29 04:33

实现如下:

#include <stdio.h>#include <stdlib.h>#define SIZE 20void bubble_sort(int array[], const int size);void swap(int *n1, int *n2);void printArray(int array[], const int size);int main(int argc, char const *argv[]){    int array[SIZE];    int count = 0;    srand(time(NULL));    for (count = 0; count < SIZE; count++) {        array[count] = rand() % SIZE + 1;    }    printArray(array, SIZE);    bubble_sort(array, SIZE);    printArray(array, SIZE);    return 0;}void bubble_sort(int array[], const int size) {    int j, k;    for (j = 0; j < size - 1; j++) {        for (k = 0; k < size - 1 - j; k++) {            if (array[k] > array[k + 1]) {                swap(&array[k], &array[k + 1]);            }        }    }}void swap(int *p1, int *p2) {    int temp = *p1;    *p1 = *p2;    *p2 = temp;}void printArray(int array[], const int size) {    printf("The current array is:\n");    int count = 0;    for (count = 0; count < size; count++) {        printf("%d ", array[count]);    }    printf("\n");}

程序使用标准函数库中函数rand产生SIZE个随机数并对其进行冒泡排序。
冒泡排序为原地稳定的排序算法,主要思想为每次循环将一个最大的数上浮到未排序的数组末尾,进行数组长度减一次循环即可排序完成,其渐近确界为Θ(n2),计算过程与插入排序类似。

0 0
原创粉丝点击