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

结果:

相关推荐
未知陨落2 分钟前
LeetCode:98.颜色分类
算法·leetcode
一只小松许️4 分钟前
深入理解:Rust 的内存模型
java·开发语言·rust
前端小马34 分钟前
前后端Long类型ID精度丢失问题
java·前端·javascript·后端
Lisonseekpan35 分钟前
Java Caffeine 高性能缓存库详解与使用案例
java·后端·spring·缓存
~kiss~41 分钟前
K-means损失函数-收敛证明
算法·机器学习·kmeans
杨小码不BUG1 小时前
Davor的北极探险资金筹集:数学建模与算法优化(洛谷P4956)
c++·算法·数学建模·信奥赛·csp-j/s
SXJR1 小时前
Spring前置准备(七)——DefaultListableBeanFactory
java·spring boot·后端·spring·源码·spring源码·java开发
mit6.8241 小时前
10.5 数位dp
c++·算法
心态特好2 小时前
详解WebSocket及其妙用
java·python·websocket·网络协议
2401_881244402 小时前
P3808 AC 自动机(简单版)
算法