Selection sort Flashcards

1
Q

Core Idea?

A
  • Repeatedly selects the smallest element from the unsorted portion of the array.
  • Swaps it with the first element in the unsorted portion
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

“Selection” ?

A

Selection of the smallest elements in each pass

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Example?

A

Initial Array: [29, 10, 14, 37, 13]

Find the smallest element (10) and swap it with the first element.
Result: [10, 29, 14, 37, 13]

Repeat for the next smallest element (13).
Result: [10, 13, 14, 37, 29]

Continue until fully sorted: [10, 13, 14, 29, 37]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Code..

A
def selection_sort(arr):
    n = len(arr)
    for i in range(n):
        # Find the smallest element in the remaining unsorted array
        min_index = i
        for j in range(i + 1, n):
            if arr[j] < arr[min_index]:
                min_index = j
        # Swap the found minimum with the first element of the unsorted part
        arr[i], arr[min_index] = arr[min_index], arr[i]

Example usage
array = [29, 10, 14, 37, 13]
print("Original Array:", array)
selection_sort(array)
print("Sorted Array:", array)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q
A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly