Java快速排序代码(递归+非递归)

讲解快排思路比较好的文章链接

快速排序—(面试碰到过好几次)
最通俗易懂的快速排序算法详解

代码

递归

package quicksort;

import java.util.Arrays;

public class QuickSortDiGui {
	public static int getPartion(int[] arr, int low, int high) {
		int partion = low;
		if(low >= high) {
			return partion;
		}
		int temp = arr[low];
		while(low<high) {
			while(arr[high]>=temp && low<high) {
				high--;
			}
			if(low<high) {
				arr[low] = arr[high];
			}
			while(arr[low]<=temp && low<high) {
				low++;
			}
			if(low<high) {
				arr[high] = arr[low];
			}
		}
		arr[low] = temp;
		partion = low;
		return partion;
	}
	
	public static void quickSort(int[] arr, int low, int high) {
		if(arr == null || arr.length == 0) {
			return;
		}
		if(low>=high) {
			return;
		}
		int partion = getPartion(arr, low, high);
		if(partion > low+1) {
			quickSort(arr, low, partion-1);
		}
		if(partion < high-1) {
			quickSort(arr, partion+1, high);
		}
	}
	
	public static void doQuickSort(int[] arr) {
		quickSort(arr, 0, arr.length-1);
	}
	
	public static void main(String[] args) {
		int[] arr = {3,1,2,4,6,7,5,3,41,10};
		doQuickSort(arr);
		System.out.println(Arrays.toString(arr));
	}
}

非递归

package quicksort;

import java.util.Arrays;
import java.util.Stack;

public class QuickSortFeiDiGui {
	public static int getPartion(int[] arr, int low, int high) {
		int partion = low;
		if(low >= high) {
			return partion;
		}
		int temp = arr[low];
		while(low<high) {
			while(arr[high]>=temp && low<high) {
				high--;
			}
			if(low<high) {
				arr[low] = arr[high];
			}
			while(arr[low]<=temp && low<high) {
				low++;
			}
			if(low<high) {
				arr[high] = arr[low];
			}
		}
		arr[low] = temp;
		partion = low;
		return partion;
	}
	
	public static void quickSort(int[] arr, int low, int high) {
		if(arr == null || arr.length == 0) {
			return;
		}
		if(low>=high) {
			return;
		}
		Stack<Integer> lowHighStack = new Stack<>();
		lowHighStack.push(low);
		lowHighStack.push(high);
		while(lowHighStack.size() > 0) {
			high = lowHighStack.pop();
			low = lowHighStack.pop();
			int partion = getPartion(arr, low, high);
			if(partion > low + 1) {
				lowHighStack.push(low);
				lowHighStack.push(partion - 1);
			}
			if(partion < high - 1) {
				lowHighStack.push(partion+1);
				lowHighStack.push(high);
			}
		}
	}
	
	public static void doQuickSort(int[] arr) {
		quickSort(arr, 0, arr.length-1);
	}
	
	public static void main(String[] args) {
		int[] arr = {3,1,2,4,6,7,5,3,41,10};
		doQuickSort(arr);
		System.out.println(Arrays.toString(arr));
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值