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

Posted yiyide266

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[C][代码实例]整型数组二分排序相关的知识,希望对你有一定的参考价值。

#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][代码实例]整型数组二分排序的主要内容,如果未能解决你的问题,请参考以下文章

NowCoderTOP17-22 二分查找/排序——持续更新ing

C语言编程 在整型有序数组中查找想要的数字并且返回下标

Java 给定一个有序整型数组, 实现二分查找

Java 给定一个有序整型数组, 实现二分查找

二分查找

Go语言 排序与搜索切片