1>
要求:
源代码:
#include <stdio.h>
#include <stdlib.h>
void output(int arr[],int len)
{for(int i=0;i<len;i++){printf("%d ",arr[i]);}puts("");
}
void bubble_sort(int arr[],int len)
{for(int i=1;i<len;i++){for(int j=0;j<len-i;j++){if(arr[j]>arr[j+1]){int t=arr[j+1];arr[j+1]=arr[j];arr[j]=t;}}}output(arr,len);
}
void select_sort(int arr[],int len)
{
for(int i=0;i<len-1;i++){int min=i;for(int j=i+1;j<len;j++){if(arr[min]>arr[j])min=j;}if(min!=i){int t=arr[min];arr[min]=arr[i];arr[i]=t;}}output(arr,len);
}void straight_insert_sort(int arr[],int len)
{int t,i,j;for ( i = 1;i < len;i++){t = arr[i];for ( j = i - 1;j >= 0 && arr[j] > t;j--){arr[j + 1] = arr[j];}arr[j + 1] = t;}output(arr,len);
}
//返回基准值下标
int one_sort(int arr[],int low,int high)
{//确定基准值int key=arr[low];//当low==high结束//循环low<highwhile(low<high){while(low<high&&key<=arr[high])high--;arr[low]=arr[high];////从low开始比较while(low<high&&key>=arr[low])low++;arr[high]=arr[low];}arr[low]=key;return low;}//快速排序
void quick_sort(int arr[],int low,int high)
{//如果只有一个元素或者没有元素int len=high+1;if(low>=high)return;//一次排序int mid=one_sort(arr,low,high);//递归左边子序列quick_sort(arr,low,mid-1);//递归右边子序列quick_sort(arr,mid+1,high);}int main(int argc, char const *argv[])
{int arr[]={23,24,12,5,33,5,34,7};int len=sizeof(arr)/sizeof(arr[0]);printf("After bubble_sort\n");bubble_sort(arr,len);printf("After select_sort\n");select_sort(arr,len);printf("After straight_insert_sort\n");straight_insert_sort(arr,len);printf("After quick_sort\n");quick_sort(arr,0,len-1);output(arr,len);return 0;
}
效果图:
2>
要求:
源代码:
#include <stdio.h>
#include <stdlib.h>
int DigitSum(int n)
{if(n==0) return 0;return n%10+DigitSum(n/10);}
int main(int argc, char const *argv[])
{int a=1729;int sum=DigitSum(a);
printf("n=%d\n",a);printf("sum=%d\n",sum);return 0;
}
c
效果图:
3>
要求:
源代码:
#include <stdio.h>
#include <stdlib.h>
#define swap(num) (num = ((num&0x55555555)<<1)+((num&0xaaaaaaaa)>>1))
int main(int argc, char const *argv[])
{int a=10;printf("a=%d\n",swap(a));printf("a=%d\n",swap(a));return 0;
}
效果图: