0
点赞
收藏
分享

微信扫一扫

数据结构与算法:快速排序


 

import java.util.Arrays;

import junit.framework.TestCase;

/**
 * 快速排序
 * 
 * @author jsczxy2
 * 
 */
public class QuickSort extends TestCase {

	@Override
	protected void setUp() throws Exception {
		super.setUp();
	}

	public void testQuickSort() {
		int[] a = { 1, 9, 3, 4, 4, 5, 7, 8, 1 };
		quickSort(a, 0, a.length - 1);
		System.out.println(Arrays.toString(a));
	}

	private void swap(int a[], int i, int j) {
		int temp = a[i];
		a[i] = a[j];
		a[j] = temp;
	}

	private int sort(int a[], int left, int right) {
		int temp = a[left];
		int i = left + 1;
		int j = right;
		while (true) {
			while (a[i] < temp && i < right) {
				i++;
			}
			while (a[j] > temp && j > left) {
				j--;
			}
			if (i >= j)
				break;
			swap(a, i, j);
		}
		a[left] = a[j];
		a[j] = temp;
		return j;
	}

	private void quickSort(int a[], int left, int right) {
		if (left < right) {
			int j = sort(a, left, right);
			quickSort(a, left, j - 1);
			quickSort(a, j + 1, right);
		}
	}

}

举报

相关推荐

0 条评论