Imitate the function of qsort to implement a general bubbling function

1. Code example (take ascending order as an example)

1. Definition of less callback function: In the sorting problem, there are ascending order and descending order. Using a callback function, the process automatically determines the sequence frame at what time to call. (Callback function is a typical usage of function pointer)

The following code means:

If a is less than b, then return a positive number

If a is equal to b, then return 0

If a is greater than b, then return a negative number

int less(int a, int b)
{
	return a-b;
}

2. Define the function pointer type Cmp (typedef: give an alias to an existing type)

typedef int(*Cmp)(int, int);

3. Bubble sort

void bubbleSort(int arr[],int len,Cmp cmp)
{
	int temp=0;
	//bound是一个边界,表示已排区间[0,bound],bound控制循环次数,直到bound=len-1,排序结束
	//待排区间(bound,cur],直到cur等于bound+1,排序结束

	for (int bound = 0; bound < len; bound++){
		for (int cur = len - 1; cur>bound; cur--){
            //传入参数前一个元素和后一个元素,cmp的返回值>0,表示arr[cur-1]>arr[cur]
            //不满足升序,所以交换位置
			if (cmp(arr[cur-1],arr[cur])>0){
				temp = arr[cur-1];
				arr[cur-1] = arr[cur];
				arr[cur] = temp;
			}
		}
	}
}

4. Main function

int main()
{
	int arr[] = {9,3,5,7,4};
	int len = sizeof(arr) / sizeof(arr[0]);
    //传入数组名,数组的长度,less函数
	bubbleSort(arr,len,less);
	for (int i = 0; i < len; i++){
		printf("%d ", arr[i]);
	}
	printf("\n");
	system("pause");
	return 0;
}

Two, running results

3. Supplement:

If you want to sort in descending order, you only need to modify the return value of the callback function less to ba.

Guess you like

Origin blog.csdn.net/weixin_43939602/article/details/109805967