Skip to content

Commit b43eabd

Browse files
authored
Update sorting.md
1 parent 4f7ab14 commit b43eabd

File tree

1 file changed

+49
-1
lines changed

1 file changed

+49
-1
lines changed

notes/sorting.md

Lines changed: 49 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,55 @@ Stability, in the context of sorting, refers to preserving the relative order of
1515
- In an **unstable** sorting algorithm, their order might be reversed in the sorted output.
1616
- In a **stable** sorting algorithm, their relative order remains unchanged.
1717

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+
```
1967

2068
This characteristic is particularly valuable in scenarios where we might perform multiple rounds of sorting based on different criteria.
2169

0 commit comments

Comments
 (0)