Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Derivative Problems of Sorting Algorithms

Derivative Problems of Sorting Algorithms

Once we have mastered basic sorting algorithms such as bubble sort and quick sort, we find that sorting is not as simple as just putting data in order.

In real-world programming and interviews, many problems are variants or derivatives of sorting algorithms.

Understanding these derivative problems helps us grasp the essence of sorting algorithms more deeply and improve our ability to solve complex problems.

This article explores several classic derivative problems of sorting algorithms, helping you build more systematic algorithmic thinking by analyzing their core ideas, solutions, and practical applications.


What are derivative problems of sorting algorithms?

Derivative problems of sorting algorithms refer to those problems thatdo not directly require sorting, but whose core ideas, algorithm flow, or data structures for solving the problem arehighly relatedto classic sorting algorithms.

Such problems usually have the following characteristics:

Let's understand this more deeply through a few specific problems below.


Classic derivative problem one: the Top K problem

Problem definition

Find thelargest (or smallest) K elements from n elements。

Practical Application Scenarios:

Comparison of solutions

Method Time Complexity Space complexity Applicable scenarios
Sort directly, then take the first K O(n log n) O(1) or O(n) when K is close to n
Bubble sort K times O(n × K) O(1) K is very small (K < 10)
Min-heap/Max-heap O(n log K) O(K) Most commonly used, K much smaller than n
Quick select algorithm O(n) average, O(n²) worst O(1) No need to be fully sorted, only Top K is needed

Method one: quick select based on the idea of quick sort

The quick select algorithm is a variant of quick sort; it does not need to fully sort the entire array, only to find the position of the K-th largest element.

Example

def

quick_select

(

nums

,

k

)

:

   

"""
    Use the quick select algorithm to find the k-th smallest element
    nums: the input array
    k: the k-th smallest element to find (1-based)
    Return: the value of the k-th smallest element
    """

   

def

partition

(

left

,

right

,

pivot_idx

)

:

       

"""Partition function, splitting the array into parts less than and greater than the pivot"""

        pivot

=

nums

[

pivot_idx

]

       

Move the pivot to the end

        nums

[

pivot_idx

]

,

nums

[

right

]

=

nums

[

right

]

,

nums

[

pivot_idx

]

       

        store_idx

=

left

       

for

i

in

range

(

left

,

right

)

:

           

if

nums

[

i

]

<

pivot:

                nums

[

store_idx

]

,

nums

[

i

]

=

nums

[

i

]

,

nums

[

store_idx

]

                store_idx +

=

1

       

       

Move the pivot to its correct position

        nums

[

right

]

,

nums

[

store_idx

]

=

nums

[

store_idx

]

,

nums

[

right

]

       

return

store_idx

   

   

def

select

(

left

,

right

,

k_smallest

)

:

       

"""Selection main function"""

       

if

left

==

right:

           

return

nums

[

left

]

       

       

Randomly choose the pivot

        pivot_idx

=

left +

(

right - left

)

//

2

       

       

Partition and obtain the pivot's final position

        pivot_idx

=

partition

(

left

,

right

,

pivot_idx

)

       

       

The pivot is exactly the k-th smallest element

       

if

k_smallest

==

pivot_idx:

           

return

nums

[

k_smallest

]

       

The k-th smallest element is in the left half

       

elif

k_smallest

<

pivot_idx:

           

return

select

(

left

,

pivot_idx -

1

,

k_smallest

)

       

The k-th smallest element is in the right half

       

else

:

           

return

select

(

pivot_idx +

1

,

right

,

k_smallest

)

   

   

k-1 because 0-based indexing is used internally

   

return

select

(

0

,

len

(

nums

)

1

,

k -

1

)

def

find_top_k

(

nums

,

k

,

largest

=

True

)

:

   

"""
    Find the largest k elements
    nums: the input array
    k: the number of elements to find
    largest: True to find the largest k, False to find the smallest k
    Return: a list of the largest k elements
    """

    n

=

len

(

nums

)

   

if

k

=

n:

       

return

sorted

(

nums

,

reverse

=

largest

)

   

   

if

largest:

       

Finding the largest k = finding the (n-k+1)-th smallest element

        kth_value

=

quick_select

(

nums

,

n - k +

1

)

       

Collect all elements greater than or equal to kth_value

        result

=

[

x

for

x

in

nums

if

x

kth_value

]

       

If the count is insufficient, add equal elements

       

while

len

(

result

)

<

k:

            result.

append

(

kth_value

)

       

return

result

   

else

:

       

Finding the smallest k = finding the k-th smallest element

        kth_value

=

quick_select

(

nums

,

k

)

        result

=

[

x

for

x

in

nums

if

x

<

kth_value

]

while

len

(

result

)

<

k:

            result.

append

(

kth_value

)

       

return

result

Test Data

test_data

=

[

3

,

2

,

1

,

5

,

6

,

4

,

9

,

8

,

7

,

0

]

print

(

"Original data:"

,

test_data

)

print

(

"The 3 largest elements:"

,

find_top_k

(

test_data.

copy

(

)

,

3

,

largest

=

True

)

)

print

(

"The 3 smallest elements:"

,

find_top_k

(

test_data.

copy

(

)

,

3

,

largest

=

False

)

)

Method two: a solution based on heap sort

The heap is a classic data structure for solving the Top K problem, especially suitable for data stream scenarios.

Example

import

heapq

def

find_top_k_with_heap

(

nums

,

k

,

largest

=

True

)

:

   

"""
    Use a heap to find the largest k elements
    nums: the input array
    k: the number of elements to find
    largest: True to find the largest k, False to find the smallest k
    Return: a list of the largest k elements
    """

   

if

largest:

       

Find the largest k: use a min-heap

        heap

=

[

]

       

for

num

in

nums:

           

if

len

(

heap

)

<

k:

               

heapq

.

heappush

(

heap

,

num

)

           

elif

num

heap

[

0

]

:  

The current element is larger than the top of the heap

               

heapq

.

heapreplace

(

heap

,

num

)

       

return

sorted

(

heap

,

reverse

=

True

)

   

else

:

       

Find the smallest k: use a max-heap (implemented by negating values)

        heap

=

[

]

       

for

num

in

nums:

           

if

len

(

heap

)

<

k:

               

heapq

.

heappush

(

heap

,

-num

)

 

Store the negated value

           

elif

num

<

-heap

[

0

]

:  

The current element is smaller than the top of the heap

               

heapq

.

heapreplace

(

heap

,

-num

)

       

return

sorted

(

[

-x

for

x

in

heap

]

)

Test the heap method

print

(

"\nUsing the heap method:"

)

print

(

"The 3 largest elements:"

,

find_top_k_with_heap

(

test_data

,

3

,

largest

=

True

)

)

print

(

"The 3 smallest elements:"

,

find_top_k_with_heap

(

test_data

,

3

,

largest

=

False

)

)


Classic derivative problem two: counting inversions

Problem definition

In an array, if an earlier element is greater than a later element, these two elements form aninversion. Count the total number of inversions in the array.

Practical Application Scenarios:

Solution: an algorithm based on merge sort

The process of merge sort can naturally count the number of inversions, which is a typical application of the divide-and-conquer idea.

Example

def

count_inversions

(

nums

)

:

   

"""
    Count the number of inversions in the array
    Use a method based on merge sort
    """

   

def

merge_sort_count

(

left

,

right

)

:

       

"""Merge sort and count inversions"""

       

if

left

=

right:

           

return

0

,

[

nums

[

left

]

]

if

left

==

right

else

[

]

       

        mid

=

(

left + right

)

//

2

       

       

Recursively count the inversions in the left and right halves

        left_count

,

left_arr

=

merge_sort_count

(

left

,

mid

)

        right_count

,

right_arr

=

merge_sort_count

(

mid +

1

,

right

)

       

       

Count the inversions crossing the midpoint

        cross_count

=

0

        merged

=

[

]

        i

=

j

=

0

       

       

while

i

<

len

(

left_arr

)

and

j

<

len

(

right_arr

)

:

           

if

left_arr

[

i

]

<=

right_arr

[

j

]

:

                merged.

append

(

left_arr

[

i

]

)

                i +

=

1

           

else

:

               

left_arr[i] > right_arr[j], forming an inversion

                merged.

append

(

right_arr

[

j

]

)

                cross_count +

=

len

(

left_arr

)

Key: all remaining elements on the left form inversions with right_arr[j]

                j +

=

1

       

       

Add the remaining elements

        merged.

extend

(

left_arr

[

i:

]

)

        merged.

extend

(

right_arr

[

j:

]

)

       

        total_count

=

left_count + right_count + cross_count

       

return

total_count

,

merged

   

   

if

not

nums:

       

return

0

   

    count

,

_

=

merge_sort_count

(

0

,

len

(

nums

)

1

)

   

return

count

Test inversion counting

test_cases

=

[

   

(

[

1

,

2

,

3

,

4

,

5

]

,

0

)

,

 

Fully sorted, 0 inversions

   

(

[

5

,

4

,

3

,

2

,

1

]

,

10

)

,

Fully reversed, inversions are C(5,2)=10

   

(

[

2

,

4

,

1

,

3

,

5

]

,

3

)

,

 

Example

   

(

[

7

,

5

,

6

,

4

]

,

5

)

,

   

Complex example

]

print

(

"\nInversion counting test:"

)

for

nums

,

expected

in

test_cases:

    result

=

count_inversions

(

nums.

copy

(

)

)

   

print

(

f

"Array {nums}: computed={result}, expected={expected}, {'correct' if result == expected else 'wrong'}"

)

The figure below shows how inversions are counted during merge sort. The key point is:when an element in the right half is smaller than a certain element in the left half, all remaining elements in the left half form inversions with that right-half element。


Classic derivative problem three: the K-th largest / K-th smallest element

This problem is a special case of the Top K problem, but has a greater variety of solutions.

Comparison of multiple solutions

Method Time Complexity Space complexity Feature
Sort, then take directly O(n log n) O(1) or O(n) Simplest and most intuitive
Quick select O(n) average O(1) Optimal average complexity
Heap method O(n log k) O(k) Suitable for data streams
Counting sort O(n + m) O(m) Suitable when the data range is small

Complete implementation example

Example

def

find_kth_smallest

(

nums

,

k

)

:

   

"""Find the k-th smallest element (1-based)"""

   

Method 1: direct sorting

   

def

method_sort

(

)

:

       

return

sorted

(

nums

)

[

k-

1

]

   

   

Method 2: quick select (implemented above)

   

def

method_quick_select

(

)

:

       

return

quick_select

(

nums.

copy

(

)

,

k

)

   

   

Method 3: heap method

   

def

method_heap

(

)

:

       

Use a max-heap to find the k-th smallest

        heap

=

[

]

       

for

num

in

nums:

           

if

len

(

heap

)

<

k:

               

heapq

.

heappush

(

heap

,

-num

)

 

The max-heap is implemented by negating values

           

elif

num

<

-heap

[

0

]

:

               

heapq

.

heapreplace

(

heap

,

-num

)

       

return

-heap

[

0

]

   

   

Method 4: counting sort (suitable when the data range is small)

   

def

method_counting

(

)

:

       

if

not

nums:

           

return

None

       

       

Find the data range

        min_val

,

max_val

=

min

(

nums

)

,

max

(

nums

)

        range_size

=

max_val - min_val +

1

       

       

Count

        count

=

[

0

]

       

for

num

in

nums:

            count

[

num - min_val

]

=

1

       

       

Find the k-th smallest

        accumulated

=

0

       

for

i

in

range

(

range_size

)

:

            accumulated +

=

count

[

i

]

           

if

accumulated

=

k:

               

return

i + min_val

       

return

None

   

   

Verify that all methods give consistent results

    result1

=

method_sort

(

)

    result2

=

method_quick_select

(

)

    result3

=

method_heap

(

)

    result4

=

method_counting

(

)

   

   

print

(

f

"\nTest for finding the {k}-th smallest element (array: {nums}):"

)

   

print

(

f

"Sorting method: {result1}"

)

   

print

(

f

"Quick select: {result2}"

)

   

print

(

f

"Heap method: {result3}"

)

   

print

(

f

"Counting method: {result4}"

)

   

   

Verify consistency

   

assert

result1

==

result2

==

result3

==

result4

,

"Different methods give inconsistent results!"

   

return

result1

Test Data

test_nums

=

[

3

,

2

,

3

,

1

,

2

,

4

,

5

,

5

,

6

]

for

k

in

[

1

,

3

,

5

,

7

]

:

    find_kth_smallest

(

test_nums.

copy

(

)

,

k

)


Classic derivative problem four: merging intervals

Problem definition

Given a set of intervals, merge all overlapping intervals.

Practical Application Scenarios:

Solution: sorting + linear scan

Example

def

merge_intervals

(

intervals

)

:

   

"""
    Merge overlapping intervals
    intervals: a list of lists, where each sublist represents an interval [start, end]
    Return: the list of merged intervals
    """

   

if

not

intervals:

       

return

[

]

   

   

Key step 1: sort by the interval start

    intervals.

sort

(

key

=

lambda

x: x

[

0

]

)

   

    merged

=

[

]

   

Key step 2: linear scan and merge

    current_start

,

current_end

=

intervals

[

0

]

   

   

for

interval

in

intervals

[

1

:

]

:

        start

,

end

=

interval

       

       

if

start

<=

current_end:  

Overlap exists

           

Merge the intervals: take the largest end point

            current_end

=

max

(

current_end

,

end

)

       

else

:  

No overlap

           

Save the current interval

            merged.

append

(

[

current_start

,

current_end

]

)

           

Start a new interval

            current_start

,

current_end

=

start

,

end

   

   

Add the last interval

    merged.

append

(

[

current_start

,

current_end

]

)

   

   

return

merged

Test interval merging

test_intervals

=

[

   

[

[

1

,

3

]

,

[

2

,

6

]

,

[

8

,

10

]

,

[

15

,

18

]

]

,

   

[

[

1

,

4

]

,

[

4

,

5

]

]

,

   

[

[

1

,

4

]

,

[

0

,

4

]

]

,

   

[

[

1

,

4

]

,

[

2

,

3

]

]

,

 

Full containment

   

[

[

1

,

4

]

,

[

0

,

2

]

,

[

3

,

5

]

]

,

 

Complex case

]

print

(

"\nInterval merging test:"

)

for

i

,

intervals

in

enumerate

(

test_intervals

,

1

)

:

    result

=

merge_intervals

(

intervals.

copy

(

)

)

   

print

(

f

"Test case {i}:"

)

   

print

(

f

" Input: {intervals}"

)

   

print

(

f

" Output: {result}"

)

   

print

(

)

Algorithm process analysis


Practical Exercise

Now, let's consolidate what we've learned through a few exercises:

Exercise 1: Sort Colors (Dutch National Flag problem)

Given an array of n elements containing red, white, and blue, sort them in place so that elements of the same color are adjacent and in the order red, white, blue.

Example

def

sort_colors

(

nums

)

:

   

"""
    Sort the color array in place
    0: red, 1: white, 2: blue
    Use the three-pointer method (similar to the partition idea of quick sort)
    """

   

Initialize the three pointers

    left

=

0

 

The right boundary of the red region

    current

=

0

 

The element currently being examined

    right

=

len

(

nums

)

1

 

The left boundary of the blue region

   

   

while

current

<=

right:

       

if

nums

[

current

]

==

0

:  

Red

            nums

[

left

]

,

nums

[

current

]

=

nums

[

current

]

,

nums

[

left

]

            left +

=

1

            current +

=

1

       

elif

nums

[

current

]

==

1

:  

white

            current +

=

1

       

else

:  

Blue

            nums

[

current

]

,

nums

[

right

]

=

nums

[

right

]

,

nums

[

current

]

            right -

=

1

           

Note: do not increment current here, because the element swapped in has not been checked yet

   

   

return

nums

Testing

colors

=

[

2

,

0

,

2

,

1

,

1

,

0

]

print

(

"Before color sort:"

,

colors

)

print

(

"After color sort:"

,

sort_colors

(

colors.

copy

(

)

)

)

Exercise 2: K-th Largest Element in an Array

Find the k-th largest element in an unsorted array.

Example

def

find_kth_largest

(

nums

,

k

)

:

   

"""
    Find the k-th largest element
    Use the quick select algorithm
    """

   

k-th largest = (n-k+1)-th smallest

    k_smallest

=

len

(

nums

)

1

   

   

def

quick_select

(

arr

,

left

,

right

,

k_small

)

:

       

if

left

==

right:

           

return

arr

[

left

]

       

       

Choose a pivot

        pivot_idx

=

(

left + right

)

//

2

        pivot

=

arr

[

pivot_idx

]

       

       

Partition

        arr

[

pivot_idx

]

,

arr

[

right

]

=

arr

[

right

]

,

arr

[

pivot_idx

]

        store_idx

=

left

       

       

for

i

in

range

(

left

,

right

)

:

           

if

arr

[

i

]

<

pivot:

                arr

[

store_idx

]

,

arr

[

i

]

=

arr

[

i

]

,

arr

[

store_idx

]

                store_idx +

=

1

       

        arr

[

right

]

,

arr

[

store_idx

]

=

arr

[

store_idx

]

,

arr

[

right

]

       

       

Recursive selection

       

if

k_small

==

store_idx:

           

return

arr

[

store_idx

]

       

elif

k_small

<

store_idx:

           

return

quick_select

(

arr

,

left

,

store_idx -

1

,

k_small

)

       

else

:

           

return

quick_select

(

arr

,

store_idx +

1

,

right

,

k_small

)

   

   

return

quick_select

(

nums.

copy

(

)

,

0

,

len

(

nums

)

1

,

k_smallest -

1

)

Testing

test_array

=

[

3

,

2

,

1

,

5

,

6

,

4

]

k

=

2

print

(

f

"\nThe {k}-th largest element in array {test_array} is: {find_kth_largest(test_array, k)}"

)