快速排序
三个区域排序
思路来源
一周刷爆LeetCode,算法大神左神(左程云)耗时100天打造算法与数据结构基础到
笔记内容
1.0
-
问题描述
在一个数组中,使用快排分出大于、等于、小于某一数值的区域
-
算法思路
- 使用两个变量bigger、smaller记录已经排好的大于、小于区域边界。
- x[i] < num, swap(x[i],x[smaller+1]),i++,smaller++
- x[i] = num, i++
- x[i] > num, swap(x[i],x[bigger - 1]),bigger --
-
代码实现
public class Quicksort { public static void main(String[] args) { int[] c = {6,7,8,5,9,6}; getResult(c,5); for (int i = 0; i < c.length; i++) { System.out.print(c[i]); } } public static void getResult(int[] target, int key){ int smaller = -1; int bigger = target.length; int i = 0; while (i < bigger){ if(target[i] < key){ int temp = target[smaller+1]; target[smaller+1] = target[i]; target[i] = temp; i++; smaller++; } else if (target[i] == key) { i++; }else { int temp = target[bigger-1]; target[bigger-1] = target[i]; target[i] = temp; bigger--; } } } }
2.0
-
问题描述
按照1.0方式,在一个数组中,使用快排排序数组
-
算法思路
- 选定一个数值中的值后进行三个区域的排序,那么等于区域位置可以被直接确定。
- 接下来再对大于小于区域做同样操作,直至固定全部数值位置。
-
代码实现
import java.util.Arrays; import java.util.Random; public class Quicksort { public static void main(String[] args) { int[] c = {2,3,9,5,7,6,4,3,5,9,8,2,1}; getResult(c); for (int i = 0; i < c.length; i++) { System.out.print(c[i]); } } public static void getResult(int[] target){ if(target.length <= 1 ){ return; } Random random = new Random(); int key = target[random.nextInt(target.length)]; int smaller = -1; int bigger = target.length; int i = 0; while (i < bigger){ if(target[i] < key){ int temp = target[smaller+1]; target[smaller+1] = target[i]; target[i] = temp; i++; smaller++; } else if (target[i] == key) { i++; }else { int temp = target[bigger-1]; target[bigger-1] = target[i]; target[i] = temp; bigger--; } } int[] left = Arrays.copyOfRange(target,0,smaller+1); int[] right = Arrays.copyOfRange(target,bigger,target.length); getResult(left); System.arraycopy(left, 0, target, 0, left.length); getResult(right); System.arraycopy(right, 0, target, bigger, right.length); } }