# APCSP (F to S) – Sorting and Searching Methods

##### Selection sort

Selection sort is a simple sort where an array is looked through and the minimum number or element is found and swapped to be put in the beginning of the array. This create two arrays, the sorted array and the unsorted array. For example if I have 1,5,7,4,2 first I will look at the second number as 1 is the smallest always, by looking at the 5 compared to all number I see 2 is the smallest and I swap it. Now the unsorted array consist of 7,4,5 while the sorted consist of 1,2. Second looking at the 7 and all numbers it is swapped with 4. This creates the unsorted array of 7,5 and the sorted of 1,2,4. After this is done over and over again until the whole array can be looked at and is in sequential order you find 1,2,4,5,7.

Below is a video showing this done with cups.

Selection sort coded algorithm

The code works using a function with a for loop and an if statement. The function allows the whole thing to work as a whole based on the list being sorted. Then the loop and the if statement work together by using the loop as the way the computer is told to go and check the number in the range at a specific location then it  uses the if statement to compare the value of the number and depending on that it will switch the number between the two locations to create an output of a sorted list.

Code:

```def selectionSort(alist):
for fillslot in range(len(alist)-1,0,-1):
positionOfMax=0
for location in range(1,fillslot+1):
if alist[location]>alist[positionOfMax]:
positionOfMax = location

temp = alist[fillslot]
alist[fillslot] = alist[positionOfMax]
alist[positionOfMax] = temp

alist = [12,1,93,19,47,66,24,43,80]
selectionSort(alist)

print("The unsorted list is: 12,1,93,19,47,66,24,43,80\n Below is the sorted list.")
print(alist)```

Output:
The unsorted list is: 12,1,93,19,47,66,24,43,80
Below is the sorted list.
[1, 12, 19, 24, 43, 47, 66, 80, 93]

CITATIONS

tutorialspoint.com. “Data Structures and Algorithms Selection Sort.” Www.tutorialspoint.com, www.tutorialspoint.com/data_structures_algorithms/selection_sort_algorithm.htm.

Dunkey. “5.8. The Selection Sort¶.” 5.8. The Selection Sort – Problem Solving with Algorithms and Data Structures,  Dunkey, interactivepython.org/runestone/static/pythonds/SortSearch/TheSelectionSort.html.

“Selection Sort.” GeeksforGeeks, Hunter1sk, 25 June 2017, www.geeksforgeeks.org/selection-sort/.

“Selection Sort.” Wikipedia, Wikimedia Foundation, 23 Jan. 2018, en.wikipedia.org/wiki/Selection_sort.