快速排序和二分查找算法的实现C语言

#include <stdio.h>


int main()
{
	void qsort(int v[], int left, int right);
	int binary_search(int v[], int left, int right, int goal);


	int a[] = {1,8,7,5,3,6,9,10,0}, i, array_length, index, goal = 0;


	array_length = sizeof(a)/sizeof(a[0]);
	printf("%d\n", array_length);
	qsort(a, 0, array_length - 1 );


	for (i = 0; i < array_length; i++)
		printf("%d ", a[i]);
	printf("\n");


	index = binary_search(a, 0, array_length - 1, goal);
	if (index != -1)
		printf("v[%d] = %d\n", index, a[index]);
	else
		printf("No find %d in array\n", goal);
	return 0;
}
/**/
void qsort(int v[], int left, int right)
{
	int last, i;
	void swap(int v[], int i, int j);


	if (left >= right)
		return;


/*	swap(v, left, (left + right)/2);*/ /* This statement can ignore */
	last = left;


	for (i = left + 1; i <= right; i++) 
		if (v[i] < v[left])
			swap(v, ++last, i);
	swap(v, left, last);
	qsort(v, left, last - 1);
	qsort(v, last + 1, right);
}
/**/
void swap(int v[], int i, int j)
{
	int temp;


	temp = v[i];
	v[i] = v[j];
	v[j] = temp;
}
/**/
int binary_search(int v[], int left, int right, int goal)
{
	int mid;


	if (left > right)
		return -1;


	mid = (left + right)/2;
	if (v[mid] == goal) {
		return mid;
	} else if (v[mid] > goal) {
		right = mid - 1;
		binary_search(v, left, right, goal);
	} else if (v[mid] < goal) {
		left = mid + 1;
		binary_search(v, left, right, goal);
	}
}
/*Reference: <<The C Programming Language 2nd>>*/

    原文作者:排序算法
    原文地址: https://blog.csdn.net/jiankangshiye/article/details/6633615
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞