指针法对数组排序

练习03-16-03

用指针法对10个整数按照从小到大的顺序进行排序

输出样例:

The original array:
 17 19 12 85 54 75  5 41 50 24
The sorted array:
  5 12 17 19 24 41 50 54 75 85
--------------------------------
Process exited after 0.02482 seconds with return value 0
请按任意键继续. . .

代码一:

#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main()
{
	srand((unsigned)time(NULL));
	int a[10],i;
	printf("The original array:\n");
	for(i=0;i<10;++i){
		a[i]=rand()%95;
		printf("%3d",a[i]);
	}
	void sort(int array[],int n);
	sort(a,10);
	printf("\nThe sorted array:\n");
	for(i=0;i<10;++i){
		printf("%3d",a[i]);
	}
	return 0;
}
void sort(int array[],int n)
{
	int i,j;
	int *pointer_1,*pointer_2;
	void swap(int *p1,int *p2);
	for(i=0;i<9;++i){
		for(j=i;j<10;++j){
			if(array[i]>array[j]){
				pointer_1=&array[i];
				pointer_2=&array[j];
				swap(pointer_1,pointer_2);
			}
		}
	}
}
void swap(int *p1,int *p2)
{
	int temp;
	temp=*p1;
	*p1=*p2;
	*p2=temp;
}

代码二:(sort函数用指针来做变换)

#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main()
{
	srand((unsigned)time(NULL));
	int a[10],i;
	printf("The original array:\n");
	for(i=0;i<10;++i){
		a[i]=rand()%95;
		printf("%3d",a[i]);
	}
	void sort(int *array,int n);
	sort(a,10);
	printf("\nThe sorted array:\n");
	for(i=0;i<10;++i){
		printf("%3d",a[i]);
	}
	return 0;
}
void sort(int *array,int n)
{
	int *i=array,*j,temp;
	for(i;i<array+9;++i){
		for(j=i+1;j<array+10;++j){
			if(*i>*j){
				temp=*j;
				*j=*i;
				*i=temp;
			}
		}
	}
}

代码三

#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#define N 10
int main()
{
	int a[N],i;
	printf("The original array:\n");
	for(i=0;i<N;++i){
		a[i]=rand()%34;
		printf("%4d",a[i]);
	}
	putchar('\n');
	printf("The sorted array:\n");
	void sort(int *x,int n);
	int *p=a;
	sort(p,N);
	while(p<a+N){
		printf("%4d",*p++);
	}
	return 0;
}
void sort(int *x, int n)
{
	int i,j,k,temp;
	for(i=0;i<n-1;++i){
		k=i;
		for(j=i+1;j<n;++j){
			if(*(x+k)>*(x+j)){
				k=j;
			}
		}
		if(k!=i){
			temp=*(x+k);
			*(x+k)=*(x+i);
			*(x+i)=temp;
		}
	}
}

 

  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值