intro
As a programmer, one of the most important technologies to learn is the sorting algorithm. Its use is commonly found in sorting data packets from the internet (what your browser does) so that you can view them correctly. Even if you won't use sorting algorithms it's a great way to practice logic and debugging in programming.
Here I'll talk about Selection Sort, one of the easiest algorithms to learn. Want to learn more about programming or algorithms? Reply below with your ideas and suggestions.
the way it sorts
Selection Sort works by going through the array multiple times, starting with the portion of the array that hasn't yet been sorted until it's at the end. During each iteration (or loop of going through the array), the lowest (or 'min') value of the array is recorded. After each iteration, the 'min' value is moved to the end of the sorted section of the array, slowly shortening the number of values that yet have to be sorted.
Take this example array: arr = [4, 2, 5, 0]
Selection Sort will work as follows. Each bullet point is an iteration of the array. You can see that the portion of the array that needs to be sorted will shrink with each iteration.
arr = [4, 2, 5, 0]
arr = [0| 4, 2, 5]
arr = [0, 2| 4, 5]
arr = [0, 2, 4| 5]
arr = [0, 2, 4, 5]
the programming
Note: There will be spoilers! I recommend you try to program this before coming here for an answer. Keep in mind that there are multiple answers based on how you code. I recommend Python as an easy language to learn and try this in.
The logic is easy, but programming it is substantially harder. I'll be using Python 3 for this example since it's the easiest for beginners to learn.
arr = [4, 2, 5, 0] # here's the array
for i in range(len(arr)): # i = 0 -> 3
min = i # default min value
for j in range(i, len(arr)): # j = i -> 3
if arr[j] < arr[min]: # if there's a new min value...
min = j # get the index of the element
arr[i], arr[min] = arr[min], arr[i] # then add it to the sorted section
We need 2 for loops: one for just going through the array and one to repeatedly go through the unsorted portion of the array. The second will keep finding the minimum value of the section until the first loop has completed, meaning that the array has been fully sorted.
Feel free to try it out! If you have any questions, reply below.
If you're interested in how AI works you are welcome to check out our series.
I've been teaching myself a bit lately, thanks for the link :)
We are happy to hear!! Stay tuned for future posts ;)
Congratulations @thenewjavaman! You have completed some achievement on Steemit and have been rewarded with new badge(s) :
You published your First Post
You made your First Vote
You got a First Vote
You made your First Comment
Click on any badge to view your own Board of Honor on SteemitBoard.
For more information about SteemitBoard, click here
If you no longer want to receive notifications, reply to this comment with the word
STOP