C language end-of-term homework generates a set of random numbers, sorts them, and keeps the set of numbers in order after inserting a number

1. Use CreateRandData(  ) , Sort(  ) and InsertValue(  ) to realize the following functions:

a . Generate 10 three-digit random positive integers and put them in the a array;

b . Sort the elements in the array in ascending order, and the sorting method is optional (selection sort, bubble sort, insertion sort);

c . Enter an integer arbitrarily and insert it into the array to keep it in order;

program:

#include<stdio.h>
#include<math.h>
#include<stdlib.h>
#include <time.h>
#define Max 100 
#define N 10 
int n = N; 
void InsertValue(int a[],int element);
void Sort(int a[]);
void CreatRandData(int a[]);
void printArr(int a[]);

int main() 
{
	int a[Max];
	int x;
	CreatRandData(a);
	printArr(a);
	Sort(a);
	printArr(a);
printf("请输入要插入的数\n");//插入一个数
	scanf("%d",&x);
	InsertValue(a,x);
	printArr(a);
	system("pause");
}
void CreatRandData(int a[]) //生成随机数
{
	int i;
	srand((int)time(NULL));
	for (i=0; i<N; i++)
	{
	a[i]=rand()%(1000-100)+100;//随机数范围
	}
		
}
void Sort(int a[])//冒泡排序
{
	int i, j, temp;
	for(i=0; i<N-1; i++)//前一个数与后一个比较,把小的放在前面
	for(j=0; j<N-1-i; j++)
	if(a[j] > a[j+1])
	{
	temp = a[j];
	a[j] = a[j+1];
	a[j+1] = temp;
	}
}
void InsertValue(int a[],int element) //插入一个数排序
{
	int j;
	if(n+1 > Max)
	return;
	for(j=n-1; j>=0; j--)
	{
		if(a[j] > element)
		a[j+1] = a[j];
		else break;
	}
	n++;
	a[j+1]=element;
}

void printArr(int a[]) 
{
	int i;
	printf("\n");	
	for(i=0; i<n; i++)
	printf("%d,",a[i]);
	printf("\n");
}

Guess you like

Origin blog.csdn.net/m0_64383325/article/details/122025838