当前位置:网站首页>C language: random generated number + merge sort
C language: random generated number + merge sort
2022-07-28 13:36:00 【Nianchi ichthyology programming】
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <assert.h>
#define MAXSIZE 10
void initArr(int arr[] , int length);
void showArr(int arr[] , int length);
void merge(int arr[],int low,int mid,int height,int *temp);
void merge_sort(int arr[],int low,int height,int *temp);
void mergeSort(int arr[],int length);
int main()
{
srand((unsigned int)time(NULL));
int arr[MAXSIZE];
printf("========== The sequence before sorting =============\n");
initArr(arr,MAXSIZE);
showArr(arr,MAXSIZE);
printf("========== Sequence after merging and sorting =============\n");
mergeSort(arr,MAXSIZE);
showArr(arr,MAXSIZE);
system("pause");
return 0;
}
void initArr(int arr[] , int length)
{
for(int i = 0 ; i < length ; i++){
arr[i] = rand()%20;
}
}
void showArr(int arr[] , int length)
{
for(int i = 0 ; i < length ; i++){
printf("%4d",arr[i]);
}
printf("\n");
}
void merge(int arr[],int low,int mid,int height,int *temp)
{
int i = low;
int j = mid+1;
int k = low;
while(i <= mid && j <= height){
temp[k++] = arr[i]<arr[j]?arr[i++]:arr[j++];
}
while(i <= mid){
temp[k++] = arr[i++];
}
while(j <= height){
temp[k++] = arr[j++];
}
for(i = low ; i <= height ; i++){
arr[i] = temp[i];
}
}
void merge_sort(int arr[],int low,int height,int *temp)
{
if(low>=height){
return;
}
int mid = low + (height - low)/2;
merge_sort(arr,low,mid,temp);
merge_sort(arr,mid+1,height,temp);
merge(arr,low,mid,height,temp);
}
void mergeSort(int arr[],int length)
{
int *temp = (int *)malloc(sizeof(int)*length);
assert(temp);
merge_sort(arr,0,length-1,temp);
free(temp);
}
边栏推荐
猜你喜欢

从手机厂高位“出走”的三个男人

JVM 内存管理 你知道多少

Map tiles: detailed explanation of vector tiles and grid tiles

Shell basic concepts and variables

《暗黑破坏神4》PS4/PS5测试版已加入PlayStation数据库

微信小程序中自定义模板

Jenkins--持续集成服务器

Shell基础概念和变量
![[报错]使用ssh登陆到另一台机器后,发现主机名还是自己|无法访问yarn8088](/img/81/641a5b3445534fc3b8c87ee6deaa64.png)
[报错]使用ssh登陆到另一台机器后,发现主机名还是自己|无法访问yarn8088

Gamestop bear market entered NFT trading, and established game retailers took advantage of Web3 to make a second spring
随机推荐
Vditor 渲染器如何做到服务端渲染(SSR)?
I copied the bottom of the liquidated NFT, but was locked by opensea
butterfly spreads
You have to apologize if you get involved in the funny shop?
[报错]使用ssh登陆到另一台机器后,发现主机名还是自己|无法访问yarn8088
Leetcode 笔记 118. 杨辉三角
屈辱、抗争、逆转,三十年,中国该赢微软一次了
Blue Bridge Training (additional interview questions) day 7
Bull spread portfolio
[matlab] IIR filter
二舅能治好年轻人的精神内耗吗?
Have a part of the game, after NFT is disabled in my world
.NET桌面开发的一些思考
Redis —— 基础篇
力扣 剑指 Offer 51. 数组中的逆序对
Shell基础概念和变量
Rust from introduction to mastery 01 introduction
gicv3 spi register
火山石投资章苏阳:硬科技,下一个10年相对确定的答案
org.apache.ibatis.exceptions.TooManyResultsException的异常排查过程