微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

为算法考试做准备--快速排序以及找第K大数的实现

package utils;

import java.util.Random;

class ArrayInts{
	private int[] theArray;
	private int nElems;
	
	public ArrayInts(int maxSize) {
		theArray = new int[maxSize];
		nElems = 0;
	}
	
	public void insert(int value) {
		theArray[nElems] = value;
		nElems++;
	}
	
	public void quickSort() {
		recQuickSort(0,nElems - 1);
	}
	
	public void recQuickSort(int left,int right) {
		if (right - left <= 0) {
			return;
		} 
		
		int pivot = theArray[right];		
		int partition = partitionIt(left,right,pivot);
		recQuickSort(left,partition - 1);
		recQuickSort(partition + 1,right);
	}
	
	public int partitionIt(int left,int right,int pivot) {
		int leftPtr = left - 1;
		int rightPtr = right;
		while (true) {
			while (theArray[++leftPtr] < pivot)
				;
			while (rightPtr > 0 && theArray[--rightPtr] > pivot)
				;
			if (leftPtr >= rightPtr)
				break;
			else
				swap(leftPtr,rightPtr);
		}
		swap(leftPtr,right);
		return leftPtr;
	}
	
	public void swap(int i1,int i2) {
		int temp = theArray[i1];
		theArray[i1] = theArray[i2];
		theArray[i2] = temp;
	}
	
	public int findKth(int left,int k) {
		if (right == left)
			return theArray[left];
		int pivot = theArray[right];
		int partition = partitionIt(left,pivot);
		int i = partition - left;
		if (i == k)
			return theArray[k];
		else if (i < k)
			return findKth(partition + 1,k - i);
		else
			return findKth(left,partition - 1,k);
	}
	
	public void display() {
		for (int j = 0; j < nElems; ++j)
			System.out.print(theArray[j] + " ");
		System.out.println();
	}
}
public class MyQuickSort {
	public static void main(String[] args) {
		ArrayInts ints = new ArrayInts(20);
		Random rand = new Random(47);
		for (int i = 0; i < 20; ++i) {
			ints.insert(rand.nextInt(100) + 1);
		}
		System.out.println("find 0th: " + ints.findKth(0,19,0));
		System.out.println("find 19th: " + ints.findKth(0,19));
		System.out.println("find 9th: " + ints.findKth(0,9));
		System.out.println("find 13th: " + ints.findKth(0,14));
		ints.quickSort();
		ints.display();
	}
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐