# Is sort() stable in Swift 5?

**URL:** <https://forums.swift.org/t/is-sort-stable-in-swift-5/21297>\
**Category:** Using Swift\
**Created:** [March 6, 2019, 7:24pm UTC](https://forums.swift.org/t/is-sort-stable-in-swift-5/21297 "2019-03-06T19:24:46Z")\
**Posts on this page:** 17\
**Page:** 1

<div class="post-metadata">

**Author:** ![Martin](https://avatars.discourse-cdn.com/v4/letter/m/73ab20/32.png) [@Martin](https://forums.swift.org/u/Martin)\
**Post date:** [March 6, 2019, 7:24pm UTC](https://forums.swift.org/t/is-sort-stable-in-swift-5/21297/1 "2019-03-06T19:24:46Z")

</div>

The documentation of the current [Sort.swift](https://github.com/apple/swift/blob/master/stdlib/public/core/Sort.swift) still states that

```
  /// The sorting algorithm is not guaranteed to be stable

```

On the other hand, the actual implementation calls

```
  /// Sorts the elements of this buffer according to `areInIncreasingOrder`,
  /// using a stable, adaptive merge sort.
  ///
  /// The adaptive algorithm used is Timsort, modified to perform a straight
  /// merge of the elements using a temporary buffer.
  @inlinable
  public mutating func _stableSortImpl(
    by areInIncreasingOrder: (Element, Element) throws -> Bool
  ) rethrows { ... }

```

Does that mean that `sort()` _is_ stable in Swift 5? I could not find that documented in the [CHANGELOG](https://github.com/apple/swift/blob/master/CHANGELOG.md) or in an evolution proposal.

Timsort is mentioned as a possible choice for a stable sort algorithm in [[Starter Proposal] Add Stable Sort to StdLib](https://forums.swift.org/t/starter-proposal-add-stable-sort-to-stdlib/9309), but that discussion ended in March '18.

There is also [SR-306 Add stable sort algorithm](https://bugs.swift.org/browse/SR-306), which is still in the Open state.

Regards, Martin

---

<div class="post-metadata">

**Author:** ![xwu](https://avatars.discourse-cdn.com/v4/letter/x/b487fb/32.png) [@xwu](https://forums.swift.org/u/xwu)\
**Post date:** [March 6, 2019, 7:31pm UTC](https://forums.swift.org/t/is-sort-stable-in-swift-5/21297/2 "2019-03-06T19:31:36Z")

</div>

If I recall, sort() is currently stable, but it is not yet _guaranteed_ to be stable (meaning, the fact that it is stable is currently an implementation detail, and a future version of Swift could ship an unstable algorithm instead).

---

<div class="post-metadata">

**Author:** ![tkrajacic](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/tkrajacic/32/1173_2.png) [@tkrajacic](https://forums.swift.org/u/tkrajacic)\
**Post date:** [March 6, 2019, 7:33pm UTC](https://forums.swift.org/t/is-sort-stable-in-swift-5/21297/3 "2019-03-06T19:33:05Z")

</div>

This makes me think it would actually be beneficial to make it intentionally unstable. Kinda like the hashValue randomization. So erroneously relying on it to be stable because not reading the documentation would surface this error.

---

<div class="post-metadata">

**Author:** ![xwu](https://avatars.discourse-cdn.com/v4/letter/x/b487fb/32.png) [@xwu](https://forums.swift.org/u/xwu)\
**Post date:** [March 6, 2019, 7:34pm UTC](https://forums.swift.org/t/is-sort-stable-in-swift-5/21297/4 "2019-03-06T19:34:47Z")

</div>

> [@tkrajacic](#):
>
> This makes me think it would actually be beneficial to make it intentionally unstable. Kinda like the hashValue randomization. So erroneously relying on it to be stable because not reading the documentation would surface this error.

The algorithm was only recently made stable in preparation for a proposal to make it guaranteed as such.

---

<div class="post-metadata">

**Author:** ![Martin](https://avatars.discourse-cdn.com/v4/letter/m/73ab20/32.png) [@Martin](https://forums.swift.org/u/Martin)\
**Post date:** [March 6, 2019, 7:44pm UTC](https://forums.swift.org/t/is-sort-stable-in-swift-5/21297/5 "2019-03-06T19:44:25Z")

</div>

Thank you for the clarification. I did now look up the relevant [commit](https://github.com/apple/swift/commit/e5c1567957e8bd159beb7ef21f5fbb25bebf34e8#diff-d8682241e4e146bde02399e918c36837):

> [stdlib] Switch to a stable sort algorithm ([#19717](https://github.com/apple/swift/pull/19717))
> 
> This switches the standard library's sort algorithm from an in-place introsort to use a modified timsort, a stable, adaptive sort that merges runs using a temporary buffer. This implementation performs straight merges instead of adopting timsort's galloping strategy.

which indeed changed the comment

```
/// The sorting algorithm is not stable.

```

to

```
/// The sorting algorithm is not guaranteed to be stable.

```

---

<div class="post-metadata">

**Author:** ![ben-cohen](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/ben-cohen/32/296_2.png) [@ben-cohen](https://forums.swift.org/u/ben-cohen)\
**Post date:** [March 6, 2019, 7:49pm UTC](https://forums.swift.org/t/is-sort-stable-in-swift-5/21297/6 "2019-03-06T19:49:23Z")

</div>

> [@xwu](#):
>
> The algorithm was only recently made stable in preparation for a proposal to make it guaranteed as such.

Exactly. It was very important that this change happened _before_ Swift shipped in an OS. Otherwise, whether or not it was stable would be determined by which version of the operating system you are running on, which would not be tenable. But since the version we're shipping in 5.0 is stable, we still have the option of officially locking that in as a guarantee in future.

Note, the new stable sort was, on balance, significantly faster in most cases than the old unstable sort so we didn't give anything up in exchange for reserving this future possibility :)

---

<div class="post-metadata">

**Author:** ![hisekaldma](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/hisekaldma/32/1146_2.png) [@hisekaldma](https://forums.swift.org/u/hisekaldma)\
**Post date:** [July 2, 2019, 9:35am UTC](https://forums.swift.org/t/is-sort-stable-in-swift-5/21297/7 "2019-07-02T09:35:17Z")

</div>

Any news on locking down the sort to always be stable?

---

<div class="post-metadata">

**Author:** ![AlexSedykh](https://avatars.discourse-cdn.com/v4/letter/a/da6949/32.png) [@AlexSedykh](https://forums.swift.org/u/AlexSedykh)\
**Post date:** [July 4, 2019, 9:21am UTC](https://forums.swift.org/t/is-sort-stable-in-swift-5/21297/8 "2019-07-04T09:21:58Z")

</div>

I would like to know. Does these sorts algorithms (in Standard Library) use some of advanced sorts approaches, like bubble sort, merge sort, bucket sort e.t.c in their internal implementations.

---

<div class="post-metadata">

**Author:** ![ben-cohen](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/ben-cohen/32/296_2.png) [@ben-cohen](https://forums.swift.org/u/ben-cohen)\
**Post date:** [July 4, 2019, 3:03pm UTC](https://forums.swift.org/t/is-sort-stable-in-swift-5/21297/9 "2019-07-04T15:03:00Z")

</div>

The library currently uses a [timsort](https://en.wikipedia.org/wiki/Timsort).

---

<div class="post-metadata">

**Author:** ![dabrahams](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/dabrahams/32/9815_2.png) [@dabrahams](https://forums.swift.org/u/dabrahams)\
**Post date:** [July 19, 2019, 11:28pm UTC](https://forums.swift.org/t/is-sort-stable-in-swift-5/21297/10 "2019-07-19T23:28:30Z")

</div>

> [@ben-cohen](#):
>
> Exactly. It was very important that this change happened _before_ Swift shipped in an OS. Otherwise, whether or not it was stable would be determined by which version of the operating system you are running on, which would not be tenable.

If such a change is considered untenable, shouldn't we lock in stability now?

---

<div class="post-metadata">

**Author:** ![ben-cohen](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/ben-cohen/32/296_2.png) [@ben-cohen](https://forums.swift.org/u/ben-cohen)\
**Post date:** [July 22, 2019, 2:37am UTC](https://forums.swift.org/t/is-sort-stable-in-swift-5/21297/11 "2019-07-22T02:37:34Z")

</div>

It depends what you mean by "lock in". Any change to the algorithm would need to be approved by the code owner, and a PR to make it unstable would close off the ABI to it ever being stable which isn't a PR we'd merge, so there's no risk of it "accidentally" becoming unstable. We're now at a point where someone could propose either to officially make `sort` stable or unstable, but either change would need to go through evolution.

---

<div class="post-metadata">

**Author:** ![DaveZ](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/davez/32/478_2.png) [@DaveZ](https://forums.swift.org/u/DaveZ)\
**Post date:** [July 22, 2019, 7:05am UTC](https://forums.swift.org/t/is-sort-stable-in-swift-5/21297/12 "2019-07-22T07:05:58Z")

</div>

I understand why a stable sort is ABI, but why would an unstable sort ABI? If the result happen to be stable later, why would that break anything?

---

<div class="post-metadata">

**Author:** ![ben-cohen](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/ben-cohen/32/296_2.png) [@ben-cohen](https://forums.swift.org/u/ben-cohen)\
**Post date:** [July 22, 2019, 3:14pm UTC](https://forums.swift.org/t/is-sort-stable-in-swift-5/21297/13 "2019-07-22T15:14:09Z")

</div>

> [@DaveZ](#):
>
> If the result happen to be stable later, why would that break anything?

This would require that if you rely on the stability of the sort, you should only do so within an availability guard, otherwise whether or not it was stable would depend on the deployment target. But because it's the same symbol, the compiler won't tell you this, you just have to know/remember, leading to some pretty unpleasant bug potential.

---

<div class="post-metadata">

**Author:** ![ben-cohen](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/ben-cohen/32/296_2.png) [@ben-cohen](https://forums.swift.org/u/ben-cohen)\
**Post date:** [July 22, 2019, 3:17pm UTC](https://forums.swift.org/t/is-sort-stable-in-swift-5/21297/14 "2019-07-22T15:17:21Z")

</div>

I guess I'm using to strong a phrasing when I say "close off the ABI to it ever being stable". It would make relying on its stability going forward very tricky in a way that's related to the ABI having been declared because the algorithm now ships in the OS.

---

<div class="post-metadata">

**Author:** ![DaveZ](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/davez/32/478_2.png) [@DaveZ](https://forums.swift.org/u/DaveZ)\
**Post date:** [July 23, 2019, 8:17am UTC](https://forums.swift.org/t/is-sort-stable-in-swift-5/21297/15 "2019-07-23T08:17:07Z")

</div>

Okay. I see your point. I think/hope that reasonable people can agree that "ABI compatibility" is a spectrum. There was a time when ABI compatibility for an OS/library meant only backward compatibility, therefore having sort be unstable in an older release and stable in a newer release would be considered reasonable. That being said, I think you're right, the definition of ABI compatibility (at least for Apple) now requires that library authors consider backwards deployment from a recent SDK as ABI, and therefore sort cannot be changed to a stable algorithm.

Even if we ignore ABI, there is an entirely different but principled argument that an essential API like "sort()" should minimize surprising behavior, therefore it should be stable. If people want to opt into an unstable sort or any other tuning parameter, then let them call "unstableSort()" or "sort(tuningParam:)", etc.

---

<div class="post-metadata">

**Author:** ![justinmeiners](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/justinmeiners/32/18192_2.png) [@justinmeiners](https://forums.swift.org/u/justinmeiners)\
**Post date:** [July 7, 2022, 9:18pm UTC](https://forums.swift.org/t/is-sort-stable-in-swift-5/21297/16 "2022-07-07T21:18:33Z")

</div>

Hoping to bring attention to this issue again. I would be interested in stability being required for the implementation.

---

<div class="post-metadata">

**Author:** ![xwu](https://avatars.discourse-cdn.com/v4/letter/x/b487fb/32.png) [@xwu](https://forums.swift.org/u/xwu)\
**Post date:** [July 7, 2022, 10:25pm UTC](https://forums.swift.org/t/is-sort-stable-in-swift-5/21297/17 "2022-07-07T22:25:55Z")

</div>

> [@Assigning a dictionary without re-hashing](https://forums.swift.org/t/assigning-a-dictionary-without-re-hashing/57699/28):
>
> Absolutely. This is a (semantic) API change, so I expect it'll require going through Swift Evolution. I've been collecting other ill-defined aspects of the stdlib -- perhaps we have a large enough batch of these now to be worth the expense of a small proposal. (Edit: [unifying and documenting the expected behavior of base properties on mutable slices](https://forums.swift.org/t/how-to-find-range-in-new-string-after-replacingcharacters-in-range-with-c/58367/17) could also be part of this, although that one also requires actual behavioral changes in some obscure corners of the stdlib.)
