c语言随机生成一个数组并插入排序
时间: 2024-06-12 21:09:44 浏览: 110
随机产生若干个数,并插入排序
生成一个随机数组并进行插入排序的C语言代码如下:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void insertionSort(int arr[], int n) {
int i, key, j;
for (i = 1; i < n; i++) {
key = arr[i];
j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
int main() {
int n, i;
printf("Enter the size of the array: ");
scanf("%d", &n);
int arr[n];
srand(time(0));
printf("Generated array: ");
for (i = 0; i < n; i++) {
arr[i] = rand() % 100; // 生成0到99之间的随机数
printf("%d ", arr[i]);
}
printf("\n");
insertionSort(arr, n);
printf("Sorted array: ");
for (i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
```
阅读全文