6.3 Sorting Algorithms Flashcards

You may prefer our related Brainscape-certified flashcards:
1
Q

What sorting algorithm is this? (Written in python)

def sort(lst: list):
    counter = 0
    for i in range(len(lst) - 1):
        while counter != len(lst) - 1:
            if lst[counter + 1] < lst[counter]:
                lst[counter], lst[counter + 1] = lst[counter + 1], lst[counter]
                print(lst)
            counter += 1
        counter = 0
    return lst
A

Bubble sort

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

What sorting algorithm is this? (Written in python)

def sort(lst: list):
    for i in range(len(lst)):
        x = lst[i]
        for j in (lst[:i]):
            if j > x:
                lst[i+1], lst[i] = lst[i], lst[i+1]
    return lst
A

Insertion sort

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

How do you merge 2 sorted lists?

A
Merge 2 sorted lists:
def merge_two_sorted_lists(lst1: list, lst2: list):
    # only works if both lists are same length
    counter = 0
    output = []
    while counter < len(lst1):
        if lst1[counter] < lst2[counter]:
            output.append(lst1[counter])
            output.append(lst2[counter])
        else:
            output.append(lst2[counter])
            output.append(lst1[counter])
        counter += 1
    return output
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Give examples of sorting algorithms

A

Bubble
Insertion
Merge

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

Bubble sort process

A

Start with left most item
Compare it with item next to it
If the left node is greater than the right node, then swap them
Repeat the above 2 steps with all the items in the list
At the end of one pass throughthe list, the largest item is at the end of the list
Repeat all above steps until the items are sorted

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

Insertion sort process

A

It sorts one data item at a time
Process:
One item is taken from a list and placed in the correct position
This is repeated until there are no more unsorted items in the list

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

Merge 2 sorted lists process

A

Read items from list A; read items from list B
Write smaller to output list, then the larger
Move to the next node
Repeat untill there are no items in the original list

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

Merge sort process

A

Divide the unsorted list into 2
Continue to divide the list until there is just one item left in the list
While merging the lists back together, sort the lists

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

Give the order of fastest sorting algorithms

A

1) Merge
2) Insertion
3) Bubble

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