Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit 71d1631

Browse filesBrowse files
committed
Create three_way_quick_sort.md
1 parent 547126e commit 71d1631
Copy full SHA for 71d1631

File tree

Expand file treeCollapse file tree

1 file changed

+86
-0
lines changed
Filter options
Expand file treeCollapse file tree

1 file changed

+86
-0
lines changed
+86Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
# 三向切分快速排序
2+
3+
## 使用场景
4+
5+
待排序数组中含有类别较少但大量重复的元素
6+
7+
## 算法思路
8+
9+
除前后两个指针外再使用两个额外的指针指向与待选元素相同的元素,遍历后将与待选元素相同的元素置换到数组中间,再对两侧分别进行排序。通过这一方法可以节省元素交换次数。
10+
11+
## 算法实现
12+
13+
```java
14+
public void sort(int[] nums) {
15+
sort(nums, 0, nums.length - 1);
16+
}
17+
18+
private void sort(int[] nums, int left, int right) {
19+
if (left < right) {
20+
// 选择首元素作为比较标志
21+
int temp = nums[left];
22+
// 设置两个指针指向与temp相同的元素范围
23+
int left_p = left;
24+
int right_p = right;
25+
for (int i = left + 1; i <= right_p; ) {
26+
// 根据比较结果进行元素交换
27+
if (nums[i] < temp) {
28+
swap(nums, left_p, i);
29+
left_p++;
30+
i++;
31+
} else if (nums[i] > temp) {
32+
swap(nums, i, right_p);
33+
right_p--;
34+
} else {
35+
i++;
36+
}
37+
}
38+
// 对两侧元素分别进行排序
39+
sort(nums, left, left_p - 1);
40+
sort(nums, right_p + 1, right);
41+
}
42+
}
43+
44+
private void swap(int[] nums, int i, int j) {
45+
int temp = nums[i];
46+
nums[i] = nums[j];
47+
nums[j] = temp;
48+
}
49+
```
50+
51+
## 经典例题
52+
53+
> [75. 颜色分类](https://leetcode-cn.com/problems/sort-colors/)
54+
>
55+
> 给定一个包含红色、白色和蓝色,一共 `n` 个元素的数组,原地对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。
56+
>
57+
> 此题中,我们使用整数 `0``1``2` 分别表示红色、白色和蓝色。
58+
59+
由于只有三种颜色,所以不需要再对比较标志两侧元素分别排序,对实现代码稍作修改即可。
60+
61+
```java
62+
public void sortColors(int[] nums) {
63+
int left = 0;
64+
int mid = 0;
65+
int right = nums.length - 1;
66+
while (mid <= right) {
67+
if (nums[mid] == 0) {
68+
swap(nums, left, mid);
69+
mid++;
70+
left++;
71+
} else if (nums[mid] == 2) {
72+
swap(nums, right, mid);
73+
right--;
74+
} else {
75+
mid++;
76+
}
77+
}
78+
}
79+
80+
private void swap(int[] nums, int i, int j) {
81+
int temp = nums[i];
82+
nums[i] = nums[j];
83+
nums[j] = temp;
84+
}
85+
```
86+

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.