SORT Flashcards
(3 cards)
Sort types
Bubble Sort: Repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order.
Insertion Sort: Builds the final sorted array one item at a time, inserting each item into its proper place.
Selection Sort: The Selection Sort algorithm finds the lowest value in an array and moves it to the front of the array.
Merge Sort: Divides the list into halves, recursively sorts them, and then merges the sorted halves.
Quick Sort: Selects a ‘pivot’ element and partitions the array into two sub-arrays according to whether they are less than or greater than the pivot. The sub-arrays are then sorted recursively.
Heap Sort: Transforms the list into a heap data structure, then repeatedly extracts the maximum element from the heap and rebuilds the heap until the list is sorted.
Insertion Sort
Insertion Sort: Builds the final sorted array one item at a time, inserting each item into its proper place.
Iterarate all walls one by one and position in correct place before correct wall.
Step 1: We start with an unsorted array.
[ 7, 12, 9, 11, 3]
Step 2: We can consider the first value as the initial sorted part of the array. If it is just one value, it must be sorted, right?
[ 7, 12, 9, 11, 3]
Step 3: The next value 12 should now be moved into the correct position in the sorted part of the array. But 12 is higher than 7, so it is already in the correct position.
[ 7, 12, 9, 11, 3]
Step 4: Consider the next value 9.
[ 7, 12, 9, 11, 3]
Step 5: The value 9 must now be moved into the correct position inside the sorted part of the array, so we move 9 in between 7 and 12.
[ 7, 9, 12, 11, 3]
Step 6: The next value is 11.
[ 7, 9, 12, > 11, 3]
Step 7: We move it in between 9 and 12 in the sorted part of the array.
[ 7, 9, 11, 12, 3]
Step 8: The last value to insert into the correct position is 3.
[ 7, 9, 11, 12, 3]
Step 9: We insert 3 in front of all other values because it is the lowest value.
[ 3,7, 9, 11, 12]
Finally, the array is sorted.
https://www.w3schools.com/dsa/dsa_algo_insertionsort.php
Bubble sort
Step 1: We start with an unsorted array.
[7, 12, 9, 11, 3]
Step 2: We look at the two first values. Does the lowest value come first? Yes, so we don’t need to swap them.
[7, 12, 9, 11, 3]
Step 3: Take one step forward and look at values 12 and 9. Does the lowest value come first? No.
[7, 12, 9, 11, 3]
Step 4: So we need to swap them so that 9 comes first.
[7, 9, 12, 11, 3]
Step 5: Taking one step forward, looking at 12 and 11.
[7, 9, 12, 11, 3]
Step 6: We must swap so that 11 comes before 12.
[7, 9, 11, 12, 3]
Step 7: Looking at 12 and 3, do we need to swap them? Yes.
[7, 9, 11, 12, 3]
Step 8: Swapping 12 and 3 so that 3 comes first.
[7, 9, 11, 3, 12]