02 Votes

Quicksort: Sort two Columns

Question by Guest | Last update on 2021-05-04 | Created on 2015-05-28

I would like to sort a table using Quicksort. However, when doing so, I do not want to consider only one column, but two columns at the same time. In other words, I would like to order by the first column first and in case that the first column has the same value, I would like to sort within this value the second column.

For example, like that:

Column 1  Columns 2
A         A
A         B
A         C
B         A
B         B
B         C
C         A
C         B

My first attempt was to apply the Quicksort algorithm two of the first column first and after that to the second column. Unfortunately, this leads to the problem that after the second column has been sorted, the values from the first column are messed up again.

How can I achieve that the values of both columns are ordered correctly and that the order of the first sorted column remains even after sorting the next column?

ReplyPositiveNegative
0Best Answer2 Votes

There are some "stable" sorting algorithms such as Mergesort. With those algorithms it is possible to sort one column first and then the next column. However, Quicksort is not stable so that we have to go another way.

If you would like to achieve the same result using Quicksort, you have to proceed as follows when comparing two values:

  • First, compare the values from the first column.
  • If the values are not equal, sort according to the first column, the values from the second column are not taken into account.
  • If the values are equal, sort according to the values from the second column.

Using this procedure, it is working with Quicksort.
Last update on 2021-05-04 | Created on 2015-05-30

ReplyPositive Negative
Reply

Related Topics

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.