首页 > 学院 > 开发设计 > 正文

插入排序算法C语言实现

2019-11-06 08:06:12
字体:
来源:转载
供稿:网友

实现如下:

#include <stdio.h>#include <stdlib.h>#define SIZE 20void insert_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); insert_sort(array, SIZE); printArray(array, SIZE); return 0;}void insert_sort(int array[], const int size) { int j, k = 1, temp; for (k = 1; k < size; k++) { temp = array[k]; for (j = k - 1; j >= 0 && array[j] > temp; j--) { swap(&array[j], &array[j + 1]); } array[j + 1] = temp; }}void swap(int *n1, int *n2) { int temp = *n1; *n1 = *n2; *n2 = 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),计算过程见算法导论第二章。


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表