How to cluster diverse elements while respecting the original sorting sequence? Suppose I have a column with a limited number of discrete values that belong to the range between 1 and 10, e.g.
5
5
3
6
5
2
4
4
5
2
6

I would like to sort those values in a way where I give priority to the chronological order new values appear (e.g. starting with a 5, then 3, then, 6 etc) but grouping similar elements together. So, for instance, from the example above I get:
5
5
5
5
3
6
6
2
2
4
4

In this reorganization, I respected the original chronological structure of elements, giving priority to the first one appearing, but grouping them by similarity.
Is there an algorithm in statistics or data science that would allow me to do that? Some kind of a combination between k-means clustering and array sorting for instance?

This task could be solved by a clustering, but it is actually a sorting problem. One of easy ways to solve it would be...
Assign each case its sequential id:
V  id
5   1
5   2
3   3
6   4
5   5
2   6
4   7
4   8
5   9
2  10
6  11

Sort your values V ascendingly (the sorting algo you use must have the property of stability, that is, for every unique V, id's must go but ascendingly in the result):
V  id
2   6
2  10
3   3
4   7
4   8
5   1
5   2
5   5
5   9
6   4
6  11

Loop through the cases and carry over: id=lag(id), for every case with V=lag(V).
V  id
2   6
2   6
3   3
4   7
4   7
5   1
5   1
5   1
5   1
6   4
6   4

Then sort ascendingly by id.
V  id
5   1
5   1
5   1
5   1
3   3
6   4
6   4
2   6
2   6
4   7
4   7

