码迷,mamicode.com
首页 > 编程语言 > 详细

[C][代码实例]整型数组二分排序

时间:2018-02-08 16:27:56      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:oid   --   done   int   swa   har   ++i   str   tin   

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>


void _qsort(void*, size_t, size_t);
void vswap(void*, void*, size_t);

int main(void)
{
	int int_1[] = {
		85,9,32,64,12,7,9,51,2,63
	};
	size_t len = sizeof(int);
	/*char int_1[] = {
		85,9,32,64,12,7,9,51,2,63
	};
	size_t len = sizeof(char);*/


	size_t count = sizeof(int_1)/len;
	void *p_1 = malloc(count*len);
	memcpy(p_1, int_1, count*len);

	_qsort(p_1, count, len);
	printf("ALL Done-----------------\n");

	size_t total_len = len * count;
	int i = 0;
	for (; i < total_len; ++i)
	{
		if(i%len != 0)
		{
			continue;
		}
		printf("%d,", *((int *)(p_1+i)));
		//printf("%d\n", *((char *)(p_1+i)));
	}
	printf("\n");

}
void _qsort(void *p,  size_t count,  size_t len)
{
	if(count == 2)
	{
		if( *((int*)(p)) > *((int*)(p+len)) )
		{
			vswap(p, p+len, len);
		}
	}
	if(count > 2)
	{
		int mid_edge = (count + count%2)/2 - 1;
		size_t total_len = len * count;
		void *p_t = malloc(total_len);
		int i = 0;
		int index = 0;
		int l_count = 0;
		int r_count = 0;
		for (; i < total_len; ++i)
		{
			if(i%len != 0)
			{
				continue;
			}
			if(i/len == mid_edge)
			{
				continue;
			}
			if( *((int*)(p+i)) <= *((int*)(p+(mid_edge*len))) )
			{
				memcpy(p_t+(index*len), p+i, len);
				printf("l :%d, val :%d\n", index, *((int*)(p+i)));
				index++;
				l_count++;
			}
		}
		//set mid
		memcpy(p_t+(index*len), p+(mid_edge*len), len);
		printf("mid_edge :%d, val :%d\n", index, *((int*)(p+(mid_edge*len))));
		index++;
		//set right
		i = 0;
		for (; i < total_len; ++i)
		{
			if(i%len != 0)
			{
				continue;
			}
			if(i/len == mid_edge)
			{
				continue;
			}
			if( *((int*)(p+i)) > *((int*)(p+(mid_edge*len))) )
			{
				memcpy(p_t+(index*len), p+i, len);
				printf("r :%d, val :%d\n", index, *((int*)(p+i)));
				index++;
				r_count++;
			}
		}

		memcpy(p, p_t, total_len);
		free(p_t);
		//recursive
		printf("%d\n", l_count);
		printf("%d\n", r_count);
		printf("Done-----------------\n");
		_qsort(p,  l_count, len);
		_qsort(p+((l_count+1)*len),  r_count, len);
	}
}



void vswap(void *p_1, void *p_2, size_t len)
{
	void *p_t = malloc(len);
	memcpy(p_t, p_1, len);
	memcpy(p_1, p_2, len);
	memcpy(p_2, p_t, len);
	free(p_t);
}

 

[C][代码实例]整型数组二分排序

标签:oid   --   done   int   swa   har   ++i   str   tin   

原文地址:https://www.cnblogs.com/yiyide266/p/8431980.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!