C/C++查找排序算法

对二分法查找、归并排序、快排做下代码总结:

参考

//二分查找非递归

int binary_find(int *arr, int left, int right, int element_find) {

	while (left <= right)
	{
		//int mid = (left + right) / 2; //left + right 可能溢出 
		int mid = left + ((right - left) >> 1);

		if (arr[mid]>element_find)
		{
			right = mid - 1;
		}
		else if (arr[mid]

//二分查找,递归

int binary_find(int *arr, int left, int right, int element_find) {
	if (left > right)
		return -1;
	int mid = left + ((right - left) >> 1);
	if (arr[mid] == element_find)
		return mid;
	else if (arr[mid] > element_find)
		return binary_find(arr, left, mid - 1, element_find);
	else
		return binary_find(arr, mid + 1, right, element_find);
}

//归并排序 递归

void merge(int *arr1, int len1, int *arr2, int len2) {

	int l1, l2, k;
	l1 = l2 = k = 0;
	int *tmp = new int[len1 + len2];

	while (l1 < len1 && l2 < len2) {
		
		if (arr1[l1] < arr2[l2])
			tmp[k++] = arr1[l1++];
		else
			tmp[k++] = arr2[l2++];
	}
	while (l1 < len1) {
		tmp[k++] = arr1[l1++];
	}
	while (l2 < len2) {
		tmp[k++] = arr2[l2++];
	}
	memcpy(arr1,tmp,(len1 + len2) * sizeof(int));

	delete[]tmp;
}

void mergeSort(int *arr, int len) {

	if (len > 1) {
		
		int len1 = len / 2;
		int len2 = len - len / 2;
		mergeSort(arr, len1);
		mergeSort(arr + len1, len2);
		merge(arr, len1, arr + len1, len2);

	}

}

//归并 非递归

//归并 非递归
void MergeSort(int k[], int n)
{
	int i, next, left_min, left_max, right_min, right_max;
	//开辟一个与原来数组一样大小的空间用来存储用  
	int *temp = (int *)malloc(n * sizeof(int));
	//逐级上升,第一次比较2个,第二次比较4个,第三次比较8个。。。  
	for (i = 1; in)
			{
				right_max = n;
			}
			//next是用来标志temp数组下标的,由于每次数据都有返回到K,  
			//故每次开始得重新置零  
			next = 0;
			//如果左边的数据还没达到分割线且右边的数组没到达分割线,开始循环  
			while (left_min0)
			{
				//把排好序的那部分数组返回该k  
				k[--right_min] = temp[--next];
			}
		}
	}
}

//快速排序

void quickSort(int *arr, int start, int end) {
			
	if (arr == NULL || start >= end)
		return;

	int key = arr[start];
	int l = start;
	int r = end;
	while (l < r) {

		while (l < r && key <= arr[r]) {
			r--;
		}
		if (l < r)
			arr[l++] = arr[r];

		while (l < r && key >= arr[l]) {
			l++;
		}
		if (l < r)
			arr[r--] = arr[l];
	}
	arr[l] = key;
	quickSort(arr,start,l-1);
	quickSort(arr,l+1,end);

}    
//快排写法2
void quickSort2(int *arr, int start, int end) {

	if (arr == NULL || start >= end)
		return;

	int key = arr[start];
	int l = start;
	int r = end;
	while (l < r) {

		while (l < r && key <= arr[r]) {
			r--;
		}

		while (l < r && key >= arr[l]) {
			l++;
		}
		if (l < r) {
			int tmp = arr[l];
			arr[l] = arr[r];
			arr[r] = tmp;
		}
	}
	arr[start] = arr[l];//j先走,不用判断最后中间数和基准数大小,直接换就可以。具体举例
	arr[l] = key;
	quickSort(arr, start, l - 1);
	quickSort(arr, l + 1, end);

}
快排2参考

你可能感兴趣的:(C/C++,笔试面试知识点)