qsort的模擬實現和練習

starry1441發表於2020-11-22

C 庫函式 - qsort()

宣告:void qsort(void *base, size_t nitems, size_t size, int (*compar)(const void , const void))

  • base – 指向要排序的陣列的第一個元素的指標。
  • nitems – 由 base 指向的陣列中元素的個數。
  • size – 陣列中每個元素的大小,以位元組為單位。
  • compar – 用來比較兩個元素的函式。

模擬實現

用的氣泡排序

#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>

int cmp_int(const void *elem1, const void *elem2)
{
	return *((int *)elem1) - *((int *)elem2);
}

void Swap(void *elem1, void *elem2, int size)
{
	for (int i = 0; i < size; i++)
	{
		char tmp = *((char *)elem1 + i);
		*((char *)elem1 + i) = *((char *)elem2 + i);
		*((char *)elem2 + i) = tmp;
	}
}

void MyQsort(void *base, int len, int size,int(*cmp)(void *elem1, void *elem2))
{
	for (int i = 0; i < len - 1; i++)
	{
		for (int j = 0; j < len - 1 - i; j++)
		{
			if (cmp((char *)base + j*size, (char *)base + (j + 1)*size) > 0)
			{
				Swap((char *)base + j*size, (char *)base + (j + 1)*size, size);
			}
		}
	}
}


int main()
{
	int arr[] = { 1, 3, 5, 7, 9, 2, 4, 6, 8, 0 };
	int len = sizeof(arr) / sizeof(arr[0]);

	MyQsort(arr, len, sizeof(int), cmp_int);

	for (int i = 0; i < len; i++)
	{
		printf("%d ", arr[i]);
	}
	return 0;
}

練習使用qsort

#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include<stdlib.h>
#include<string.h>
#include<assert.h>

int cmp1(const void *a, const void *b)
{
	assert(a);
	assert(b);
	return (*(unsigned char *)a - *(unsigned char *)b);
}

int cmp2(const void *a, const void *b)
{
	assert(a);
	assert(b);
	return strcmp((char *)*(int *)a, (char *)*(int *)b);
}

int cmp3(const void *a, const void *b)
{
	assert(a);
	assert(b);
	return (*(unsigned int *)a - *(unsigned int *)b);;
}

int cmp4(const void *a, const void *b)
{
	assert(a);
	assert(b);
	return (((*(double *)a - *(double *)b) > 0) ? 1 : -1);
}


int main()
{
	int i = 0;
	char c[10] = "adicfjgheb";
	char *s[5] = { "aaa", "ddd", "iii", "ccc", "fff" };
	int a[10] = { 1, 3, 4, 5, 8, 0, 9, 7, 2, 6 };
	double b[10] = { 0.3, 1.7, 2.5, 0.1, 3.9, 2.1, 0.4, 0.2, 1.5, 2.3 };
	qsort(c, 10, sizeof(char), cmp1);
	qsort(s, 5, sizeof(char *), cmp2);
	qsort(a, 10, sizeof(int), cmp3);
	qsort(b, 10, sizeof(double), cmp4);
	for (i = 0; i < 10; i++)
	{
		printf("%c ", c[i]);
	}
	printf("\n");
	for (i = 0; i < 5; i++)
	{
		printf("%s ", s[i]);
	}
	printf("\n");
	for (i = 0; i < 10; i++)
	{
		printf("%d ", a[i]);
	}
	printf("\n");
	for (i = 0; i < 10; i++)
	{
		printf("%lf ", b[i]);
	}
	printf("\n");
	return 0;
}

相關文章