块状局部有序整体无序数据结构 - FewUniqueKeys

本文介绍了一种特定场景下的数组排序——包含少量唯一键的情况。此类排序常见于实践,期望算法能在O(n)时间内完成。文章通过示例展示了传统2-way快速排序在此场景下可能退化至O(n^2),并提出采用3-way快速排序或Shell排序来解决该问题。
package com.victor.sort.seeds;

import java.util.ArrayList;

public class FewUniqueKeys extends Seeds {

	@Override
	protected ArrayList<Integer> doGenerate(int size) {
		ArrayList<Integer> seedsList = new ArrayList<Integer>();
		int requiredSize = getSize();
		java.util.Random rd = new java.util.Random();
		int numberOfKeys = rd.nextInt(5) + 5;
		int[] values = new int[numberOfKeys];
		for(int i=0;i<numberOfKeys;i++)
		{
			values[i] = rd.nextInt(10000);
		}
		for(int i=0;i<requiredSize;i++)
		{
			int nextValue = rd.nextInt(requiredSize)%numberOfKeys;
			seedsList.add(values[nextValue]);
		}
		return seedsList;
	}

	@Override
	public String getDescriptions() {
		return "Sorting an array that consists of a small number of unique keys is common in practice. " +
				"One would like an algorithm that adapts to O(n) time when the number of unique keys is O(1). " +
				"In this example, there are 4 unique keys. The traditional 2-way partitioning quicksort exhibits " +
				"its worse-case O(n2) behavior here. For this reason, " +
				"any quicksort implementation should use 3-way partitioning, " +
				"where the array is partitioned into values less than, equal, " +
				"and greater than the pivot. Because the pivot values need not be sorted recursively, " +
				"3-way quick sort adapts to O(n) time in this case. Shell sort also adapts to few unique " +
				"keys, though I do not know its time complexity in this case.";
	}

	@Override
	public String getName() {
		return "Few Unique Keys";
	}
	
	public static void main(String[] args)
	{
		Seeds rd = new FewUniqueKeys();
		rd.setSize(100);
		rd.generate();
		rd.print();
	}

}


转载于:https://my.oschina.net/readjava/blog/304454

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值