实现如下:
#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个随机数并对其进行插入排序。 插入排序为原地稳定的排序算法,主要思想每次将一个数插入到已排序的数组中去,其渐近确界为
新闻热点
疑难解答