快速排序

[85.36] [5.65] [0.00] [123.11] [58.77] [212.88] [0.02] [0.00] [0.00] [9999.00]

[0.02] [5.65] [0.00] [0.00] [58.77] [0.00] [85.36] [212.88] [123.11] [9999.00]

[0.00] [0.00] [0.00] [0.02] [58.77] [5.65] [85.36] [212.88] [123.11] [9999.00]

[0.00] [0.00] [0.00] [0.02] [58.77] [5.65] [85.36] [212.88] [123.11] [9999.00]

[0.00] [0.00] [0.00] [0.02] [58.77] [5.65] [85.36] [212.88] [123.11] [9999.00]

[0.00] [0.00] [0.00] [0.02] [5.65] [58.77] [85.36] [212.88] [123.11] [9999.00]

[0.00] [0.00] [0.00] [0.02] [5.65] [58.77] [85.36] [123.11] [212.88] [9999.00]

 

看起来像二分排序

 

#include <stdio.h>
#include <string.h>
#include <malloc.h>

typedef struct trans{
	double amt;
	char   name[100];

} trans_t;

trans_t *g;

void print_d()
{	trans_t *p = g;
	for(int i=0;i<10;i++)
	{
		printf("[%.2f] ",p->amt);
		p++;
	}
	printf("\n");
}

void make_data(trans_t **p)
{
	trans_t *q;
	trans_t  d;
	strcpy(d.name,"lalalala");
	q = (trans_t *)malloc(sizeof(trans_t)*10);
	*p = q;
	for(int i=0;i<10;i++){
		switch(i){
		case 0: d.amt = 85.36;break;
		case 1: d.amt = 5.65;break;
		case 2: d.amt = 0;break;
		case 3: d.amt = 123.11;break;
		case 4: d.amt = 58.77;break;
		case 5: d.amt = 212.88;break;
		case 6: d.amt = 0.02;break;
		case 7: d.amt = 0;break;
		case 8: d.amt = 0;break;
		case 9: d.amt = 9999.00;break;
		default : break;
		}
		
		memcpy(q,&d,sizeof(trans_t));
		q++;
	}
}

void quicksort(trans_t *d,int n)
{
    trans_t *p,*q;
	trans_t dt;
	double tmp;
	p = d;
	q = d+n-1;

    if(p>=q)
		return;
    tmp=d->amt; //tmp中存的就是基准数,即下面一个循环后,amt左边的数都大于右边的数
    while(p!=q)
    {
		//顺序很重要,要先从右边开始找
		while(q->amt >=tmp && p<q)
			q--;
		//再找右边的
		while(p->amt <=tmp && p<q)
			p++;
		//交换两个数在内存中的位置
		if(p<q)
		{
			memcpy(&dt,p,sizeof(trans_t));
			memcpy(p,q,sizeof(trans_t));
			memcpy(q,&dt,sizeof(trans_t));
		}
		
    }
	memcpy(&dt,p,sizeof(trans_t));
	memcpy(p,d,sizeof(trans_t));
	memcpy(d,&dt,sizeof(trans_t));
	print_d();
    quicksort(d,p-d);//继续处理左边的,这里是一个递归的过程
    quicksort(p+1,n-(p-d)-1);//继续处理右边的 ,这里是一个递归的过程
}





int main()
{
	trans_t *p;
	
	make_data(&p);
	g = p;
	print_d();
	quicksort(p,10);
	return 0;
}

 

posted on 2017-09-28 18:26  阮減显  阅读(132)  评论(0编辑  收藏  举报

导航