寒假作业-day5

1>现有无序序列数组为23,24,12,5,33,5347,请使用以下排序实现编程

函数1:请使用冒泡排序实现升序排序

函数2:请使用简单选择排序实现升序排序

函数3:请使用直接插入排序实现升序排序

函数4:请使用插入排序实现升序排序

代码:

cpp 复制代码
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

void bubble(int a[],int n){
	for(int i=1;i<n;i++){
		for(int j=0;j<n-i;j++){
			if(a[j]>a[j+1]){
				int temp=a[j];
				a[j]=a[j+1];
				a[j+1]=temp;
			}
		}
	}
}
void simple(int b[],int n){
	for(int i=0;i<n-1;i++){
		int min=i;
		for(int j=i+1;j<n;j++){
			if(b[min]>b[j])
				min=j;
		}
		if(min!=i){
			int temp=b[min];
			b[min]=b[i];
			b[i]=temp;
		}
	}
}
void dir_insert(int c[],int n){
	int j;
	for(int i=1;i<n;i++){
		int temp=c[i];
		for(j=i-1;j>=0&&c[j]>temp;j--){
				 c[j+1]=c[j];
		}
		c[j+1]=temp;
	}
}

int sort(int arr[],int low,int high){
	int key=arr[low];
	while(low<high)
	{
		while(low<high&&key<=arr[high])
			high--;
		arr[low]=arr[high];
		while(low<high&&key>=arr[low])
			low++;
		arr[high]=arr[low];
	}
	arr[low]=key;
	return low;
}
void quick(int arr[],int low,int high){
	if(low>=high)
		return;
	int mid=sort(arr,low,high);
	quick(arr,low,mid-1);
	quick(arr,mid+1,high);
}

void output(int arr[],int len){
	for(int i=0;i<len;i++)
		printf("%d\t",arr[i]);
	puts("");
}
int main(int argc,const char *argv[]){
	int a[]={23,24,12,5,33,5,34,7};
	int len=sizeof(a)/sizeof(a[0]);
	bubble(a,len);
	output(a,len);
	int b[]={23,24,12,5,33,5,34,7};
	simple(b,len);
	output(b,len);
	int c[]={23,24,12,5,33,5,34,7};
	dir_insert(c,len);
	output(c,len);
	int d[]={23,24,12,5,33,5,34,7};
	quick(d,0,len-1);
	output(d,len);
	return 0;
}

结果:

2>请编程实现

写个递归函数 DigitSum(n),输入一个非负整数,返回组成它的数字之和

例如:调用 DigitSum(1729),则返回 1+7+2+9,它的和是 19

输入1729,输出 19

代码:

cpp 复制代码
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

int DigitSum(int n){
	if(n==0)
		return 0;
	int temp=n;
	temp%=10;
	n/=10;
	return temp+DigitSum(n);
}

int main(int argc,const char *argv[]){
	int num=1729;
	printf("%d\n",DigitSum(num));
	return 0;
}

结果:

3>请编程实现

写一个宏,可以将一个 int 型整数的二进制位的奇数位和偶数位交换

代码:

cpp 复制代码
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define SWAP_BIT(n) (n=((n&0xaaaaaaaa)>>1)+((n&0x55555555)<<1))

int main()
{
	int a = 10;
	//00000000000000000000000000001010 ->10
	// 其奇偶位交换后得 :
	//00000000000000000000000000000101 ->5
	SWAP_BIT(a);
	printf("a=%d\n", a);
	return 0;
}

结果:

相关推荐
IUGEI29 分钟前
从原理到落地:DAG在大数据SLA中的应用
java·大数据·数据结构·后端·算法
云深麋鹿31 分钟前
五.排序笔记
c语言·数据结构·算法·排序算法
spcier7 小时前
图论拓扑排序-Kahn 算法
算法·图论
知星小度S7 小时前
动态规划(一)——思想入门
算法·动态规划
ysa0510307 小时前
动态规划-逆向
c++·笔记·算法
燃于AC之乐7 小时前
我的算法修炼之路--7—— 手撕多重背包、贪心+差分,DFS,从数学建模到路径DP
c++·算法·数学建模·深度优先·动态规划(多重背包)·贪心 + 差分
Whisper_Sy7 小时前
Flutter for OpenHarmony移动数据使用监管助手App实战 - 网络状态实现
android·java·开发语言·javascript·网络·flutter·php
chinesegf7 小时前
文本嵌入模型的比较(一)
人工智能·算法·机器学习
乂爻yiyao7 小时前
1.1 JVM 内存区域划分
java·jvm
We་ct8 小时前
LeetCode 6. Z 字形变换:两种解法深度解析与优化
前端·算法·leetcode·typescript