利用快速排序中的切分函数寻找数组主元素

本文介绍了一种用于查找数组中是否存在主元素(超过一半元素相同)的算法,并提供了完整的C语言实现代码。通过查找中位数并验证其是否为数组的主元素来解决问题。

如果一个数组A[1..n]中超过半数的元素都相同时,该数组被称为含有主元素

算法:利用切分函数查找中位数,遍历数组如果与中位数相等的元素个数大于数组长度一半,那么则存在主元素,这个中位数即主元素。

代码:

#include <stdio.h>

void swap(int *a,int *b)
{
	int	temp = *a;
	*a = *b;
	*b = temp;
}

int hoare_partition(int a[],int left,int right)
{
	int i,j,pivot;
	pivot = a[left];
	i = left - 1;
	j = right + 1;
	while(1)
	{
		do
		{
			j--;
		}while(a[j]>pivot);

		do
		{
			i++;
		}while(a[i]<pivot);

		if(i<j)
			swap(a+i,a+j);
		else
			return j;
	}	
}

int partition(int a[],int left,int right)
{
	int i,j;
	int pivot = a[right];
	i = left - 1;
	for(j=left;j<right;j++)
	{
		if(a[j]<=pivot)
		{
			i++;
			swap(a+i,a+j);
		}
	}
	swap(a+i+1,a+right);
	return i+1;
}
int selectKth(int a[],int left,int right,int K)
{
	int idx = partition(a,left,right);
	if(idx-left+1 == K)
		return idx;
	else if (idx-left+1 < K)
		return selectKth(a,idx+1,right,K-(idx-left+1));
	else
		return selectKth(a,left,idx-1,K);
}

void qSort(int a[],int left,int right)
{
	if(left<right){
		int idx = partition(a,left,right);
		qSort(a,left,idx-1);
		qSort(a,idx+1,right);
	}
}
int major_element(int a[],int left,int right)
{
	/* major element exist if non-negative is returned. */
	if(left<=right){
		int mid = selectKth(a,left,right,(right-left+2)>>1);

		int cnt = 0;
		for(int i=left;i<=right;i++){
			if(a[i] == a[mid])
			cnt++;
		}
		if(cnt>(right-left+1)>>1)
			return mid;
	} 
	return -1;
}

void showArray(int a[],int l,int r)
{
	for(int i=l;i<=r;i++)
		printf("%-3d",a[i]);
	printf("\n");
}
int main(){
	int a[] = {1,4,2,3,4,5,4,4,4};
	int b[] = {1,3,2};
	int c[] = {2};
	int d[] = {4,4,4,4,1,2,3,5};
	showArray(a,0,8);
	showArray(b,0,2);
	showArray(c,0,0);
	showArray(d,0,7);

	int m = major_element(a,0,8);
	printf("Major element exist in List a? %s \n",m>-1?"Yes!":"No!");
	
	printf("%-3d\n",a[m]);
	showArray(a,0,8);
	
	m = major_element(b,0,2);
	printf("Major element exist in List b? %s \n",m>-1?"Yes!":"No!");
	
	m = major_element(c,0,0);
	printf("Major element exist in List c? %s \n",m>-1?"Yes!":"No!");
	
	m = major_element(d,0,7);
	printf("Major element exist in List d? %s \n",m>-1?"Yes!":"No!");

	qSort(a,0,8);
	qSort(b,0,2);
	qSort(c,0,0);
	qSort(d,0,7);
	showArray(a,0,8);
	showArray(b,0,2);
	showArray(c,0,0);
	showArray(d,0,7);
}
测试结果:

1  4  2  3  4  5  4  4  4  (Array a)
1  3  2                    (Array b)
2  			   (Array c)	
4  4  4  4  1  2  3  5     (Array d)
Major element exist in List a? Yes! 
4  
1  4  2  3  4  4  4  4  5  
Major element exist in List b? No! 
Major element exist in List c? Yes! 
Major element exist in List d? No! 
1  2  3  4  4  4  4  4  5  
1  2  3  
2  
1  2  3  4  4  4  4  5  



<think>我们被要提供一个Java的快速排序算法实现示例。根据引用内容,我们可以参考多个实现。 引用[1]提供了一个Java实现的快速排序,其中方法为quickSort,分区方法为partition,并选择最后一个元素作为基准。 引用[2]和引用[3]也提到了快速排序的基本原理和实现。 引用[4]和引用[5]则提供了一些优化方法和应用场景。 我们将按照以下步骤实现: 1. 选择一个基准元素(pivot)。可以选择第一个、最后一个、随机一个或者中间值等。 2. 分区(partition):重新排列数组,使得所有小于基准的元素放在基准前面,大于基准的放在后面。分区完成后,基准元素处于其正确位置。 3. 递归地对基准左右两边的子数组进行快速排序。 这里我们采用引用[1]的实现方式,选择最后一个元素作为基准,并实现分区方法。 注意:快速排序有多个版本,我们这里实现的是Lomuto分区方案,另一种常见的分区方案是Hoare分区方案。 我们将编写一个类,包含快速排序的静态方法。 同时,根据引用[5]提到的优化,我们可以考虑: - 随机选取基准(避免最坏情况) - 小序列时使用插入排序(优化递归) - 处理相同元素(三向切分) 但作为基础示例,我们先实现一个基础版本,然后可以再展示一个优化版本(随机基准)。 基础版本(固定基准,选择最后一个元素): 步骤: - 在分区方法中,设置基准为最后一个元素。 - 初始化一个索引i(表示小于基准的最后一个元素的位置),从low-1开始。 - 遍历数组从low到high-1,如果当前元素小于等于基准,则将其与i+1位置的元素交换,并递增i。 - 最后将基准(arr[high])与i+1位置的元素交换,这样基准就放在了正确的位置。 - 返回基准的索引(i+1)。 递归方法: - 如果low小于high,则进行分区,然后递归排序左右两部分。 我们还可以实现一个随机基准的版本,以避免在数组已经有序时出现最坏时间复杂度O(n^2)。 随机基准版本: - 在分区前,随机选择一个位置与最后一个元素交换,然后再以最后一个元素作为基准。 下面我们分别实现这两个版本。 注意:为了清晰,我们提供两个示例:基础版本和随机基准版本。 首先,基础版本:</think>### Java 快速排序算法实现示例 快速排序是一种基于**分治法**的高效排序算法,其核心思想是通过递归地将数组划分为较小和较大的两部分来实现排序。以下是标准实现和优化版本: #### 基础实现(固定基准) ```java public class QuickSort { // 快速排序入口方法 public static void quickSort(int[] arr, int low, int high) { if (low < high) { int pi = partition(arr, low, high); // 获取基准位置 quickSort(arr, low, pi - 1); // 递归排序左子数组 quickSort(arr, pi + 1, high); // 递归排序右子数组 } } // 分区函数(Lomuto方案) private static int partition(int[] arr, int low, int high) { int pivot = arr[high]; // 选择最后一个元素作为基准 int i = low - 1; // 小于基准的边界指针 for (int j = low; j < high; j++) { if (arr[j] <= pivot) { i++; // 交换元素 int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } // 将基准放到正确位置 int temp = arr[i + 1]; arr[i + 1] = arr[high]; arr[high] = temp; return i + 1; } // 测试用例 public static void main(String[] args) { int[] arr = {10, 80, 30, 90, 40, 50, 70}; quickSort(arr, 0, arr.length - 1); System.out.println("排序结果: " + Arrays.toString(arr)); // 输出: [10, 30, 40, 50, 70, 80, 90] } } ``` #### 优化版本(随机基准 + 三数取中) ```java public class OptimizedQuickSort { public static void quickSort(int[] arr, int low, int high) { if (high - low < 16) { // 小数组使用插入排序 insertionSort(arr, low, high); return; } if (low < high) { int pi = randomizedPartition(arr, low, high); quickSort(arr, low, pi - 1); quickSort(arr, pi + 1, high); } } // 随机选择基准 private static int randomizedPartition(int[] arr, int low, int high) { // 三数取中法选择基准 int mid = low + (high - low) / 2; if (arr[mid] < arr[low]) swap(arr, low, mid); if (arr[high] < arr[low]) swap(arr, low, high); if (arr[mid] < arr[high]) swap(arr, mid, high); return partition(arr, low, high); } // Hoare分区方案(减少交换次数) private static int partition(int[] arr, int low, int high) { int pivot = arr[high]; int i = low, j = high - 1; while (true) { while (i <= j && arr[i] < pivot) i++; while (i <= j && arr[j] > pivot) j--; if (i >= j) break; swap(arr, i++, j--); } swap(arr, i, high); return i; } // 插入排序辅助函数 private static void insertionSort(int[] arr, int low, int high) { for (int i = low + 1; i <= high; i++) { int key = arr[i]; int j = i - 1; while (j >= low && arr[j] > key) { arr[j + 1] = arr[j]; j--; } arr[j + 1] = key; } } private static void swap(int[] arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } ``` ### 关键特性说明 1. **时间复杂度**: - 平均情况:$O(n \log n)$ - 最坏情况(已排序数组):$O(n^2)$ - 优化后最坏情况概率显著降低[^3] 2. **空间复杂度**: - 递归栈深度:$O(\log n)$(优化后) - 属于**原地排序**算法[^4] 3. **优化策略**: - **随机基准**:避免已排序数组的最坏情况 - **三数取中**:选择更合理的基准值 - **小数组切换**:对长度<16的子数组用插入排序 - **Hoare分区**:减少元素交换次数[^5] ### 适用场景 1. 大规模乱序数组排序(平均性能最优)[^4] 2. 内存敏感场景(原地排序特性) 3. 数据频繁变动的动态数据集[^4] 4. 对稳定性无要的场景(快速排序不稳定) > ⚠️ 注意:当数据已基本有序时,建议使用插入排序;当需要稳定排序时,建议使用归并排序。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值