C language uses pointers to implement selection method and bubbling method to sort numbers
I
just learned the pointer chapter in the preface . Most of the exercises I encountered were to rewrite the previously written code using the pointer method, but to be honest, many of them are not as simple as I thought, and I don’t think it is necessary, but it is said The pointer to the linked list is very useful, so I hope everyone will pay attention to the pointer and share this for everyone to see.
Selective sorting
//选择算法
//指针选择法排序
#include<stdio.h>
main(){
int a[10],i,j,*p; //变量全部初始化
printf("please input ten nums devise keyboard!\n");
p=a;
for(i=0;i<10;i++){
//从键盘输入数组元素
scanf("%d",&*(p++));
}
p=a; //核心部分选择法排序
for(i=0;i<10-1;i++){
//执行N-1次(第一个与下一个换,最后一个不用换)
int min = i; //这个min记录的i,就是将第i个与全数组比较调换
for(j=i+1;j<10;j++){
//j=i+1;会从还没排好的地方开始
if(*(p+j)<*(p+min)){
//逐一比较找出目标值
min = j;
}
}
if(min!=i){
//如果目标值不是当前值就开始调换
int temp;
temp = *(p+i);
*(p+i) = *(p+min);
*(p+min) = temp;
}
}
p=a;//打印排序完成后的数组元素
for(i=0;i<10;i++){
printf("%d ",*(p++));
}
printf("\n");
}
Bubble sorting
//冒泡法 mine 非函数
#include<stdio.h>
main(){
int a[1000]; //划定一个最大的数组长度
int *p,n,i,j;
printf("请输入数组的长度:");
scanf("%d",&n);
printf("请输入数组各元素:\n");
p=a; //开始从键盘接收数组元素
for(i=0;i<n;i++){
scanf("%d",&*(p++));
}
p=a; //冒泡法核心
for(i=0;i<n-1;i++){
//也是一样的两两一比,最后一个不需要
for(j=0;j<n-1-i;j++){
//j用来记录比较次数,仅比较未达标的
if(*(p+j)>*(p+j+1)){
int temp;
temp=*(p+j);
*(p+j)=*(p+j+1);
*(p+j+1)=temp;
}
}
}
p=a;
for(i=0;i<n;i++){
printf("%d ",*(p++));
}
}
Everything is almost the same here. This is mainly written for new beginners like me. We haven't learned the function yet. The code we wrote is written in the C environment. After all, I don’t remember anything when I come to school after the vacation. .
Give yourself a like every day!
Hope to bring you some help.