寒假作业-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;
}

结果:

相关推荐
一只会写代码的猫10 小时前
面向高性能计算与网络服务的C++微内核架构设计与多线程优化实践探索与经验分享
java·开发语言·jvm
萤丰信息11 小时前
智慧园区能源革命:从“耗电黑洞”到零碳样本的蜕变
java·大数据·人工智能·科技·安全·能源·智慧园区
曹牧12 小时前
Eclipse为方法添加注释
java·ide·eclipse
我叫张小白。12 小时前
Spring Boot拦截器详解:实现统一的JWT认证
java·spring boot·web·jwt·拦截器·interceptor
Gerardisite14 小时前
如何在微信个人号开发中有效管理API接口?
java·开发语言·python·微信·php
gfdhy15 小时前
【c++】哈希算法深度解析:实现、核心作用与工业级应用
c语言·开发语言·c++·算法·密码学·哈希算法·哈希
闲人编程15 小时前
Python的导入系统:模块查找、加载和缓存机制
java·python·缓存·加载器·codecapsule·查找器
百***060115 小时前
SpringMVC 请求参数接收
前端·javascript·算法
故渊ZY15 小时前
Java 代理模式:从原理到实战的全方位解析
java·开发语言·架构
匿者 衍15 小时前
POI读取 excel 嵌入式图片(支持wps 和 office)
java·excel