You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: notes/sorting.md
+49-1Lines changed: 49 additions & 1 deletion
Original file line number
Diff line number
Diff line change
@@ -15,7 +15,55 @@ Stability, in the context of sorting, refers to preserving the relative order of
15
15
- In an **unstable** sorting algorithm, their order might be reversed in the sorted output.
16
16
- In a **stable** sorting algorithm, their relative order remains unchanged.
17
17
18
-
For example, consider a sequence of colored balls, each with a number. If we sort them based on their number using a stable sorting method, two balls with the same number will retain their original order in terms of color.
18
+
Sure, let's use an example with characters and their indices to illustrate both stable and unstable sorting.
19
+
20
+
#### Example
21
+
22
+
Consider the following pairs of characters and their indices:
23
+
24
+
```
25
+
[A0] [C1] [B2] [A3] [B4]
26
+
```
27
+
28
+
#### Stable Sort
29
+
30
+
When we sort these pairs alphabetically by character using a stable sorting method, pairs with the same character retain their original order in terms of indices.
31
+
32
+
1. Sort the character 'A':
33
+
```
34
+
[A0] [A3] [C1] [B2] [B4]
35
+
```
36
+
37
+
2. Next, sort the character 'B', retaining the original order of indices:
38
+
```
39
+
[A0] [A3] [B2] [B4] [C1]
40
+
```
41
+
42
+
So, the stable sorted sequence is:
43
+
44
+
```
45
+
[A0] [A3] [B2] [B4] [C1]
46
+
```
47
+
48
+
#### Unstable Sort
49
+
50
+
When we sort these pairs alphabetically by character using an unstable sorting method, pairs with the same character may not retain their original order in terms of indices.
51
+
52
+
1. Sort the character 'A':
53
+
```
54
+
[A3] [A0] [C1] [B2] [B4]
55
+
```
56
+
57
+
2. Next, sort the character 'B', without retaining the original order of indices:
58
+
```
59
+
[A3] [A0] [B4] [B2] [C1]
60
+
```
61
+
62
+
So, the unstable sorted sequence is:
63
+
64
+
```
65
+
[A3] [A0] [B4] [B2] [C1]
66
+
```
19
67
20
68
This characteristic is particularly valuable in scenarios where we might perform multiple rounds of sorting based on different criteria.
0 commit comments