9953330565 Low Rate Call Girls In Rohini Delhi NCR
Sorting arrays
1. Sorting Arrays
• There are many different algorithms for sorting arrays, some are easier to code and some have a
faster computation time.
• Why sort an array?
– In some cases, especially when searching for elements in an array, it is beneficial to sort your
array in lexicographical order. This could greatly reduce time spent searching through an array as
you will see later.
• The 2 main sorting algorithms for arrays are:
– Selection Sort
– Bubble Sort
Selection Sort
• Consider having an array: {5, 7, 2, 15, 3}
• Step 1 of the selection sort algorithm is to find the smallest value, which is 2.
• Step 2, swap the value with the first position, which would give us: {2, 7, 5, 15, 3}
• Repeating these steps we find that 3 is the next smallest number, when we swap it for the next
position we get: {2, 3, 5, 15, 7}
• We would repeat this until the array is sorted or to be more specific when we reach array.
length -1 at which point if the second last element was smaller than the last we would swap and
the array would be sorted otherwise the array is sorted.
{2, 3, 5, 7, 15}
2. Bubble Sort
• Bubble sort, also known as exchange sort, is another sorting algorithm that is fairly simple but
very inefficient on large lists.
• The algorithm works as follows:
1. Compare 2 adjacent values (those at indexes 0 and 1)
2. If they are in the wrong order, swap them
3. Continue this with the next two adjacent values (those at indexes 1 and 2) and on through the
rest of the list.
4. Repeat steps 1 through 3 until array is sorted.
This video is a great visual representation of how this algorithm works:
https://www.youtube.com/watch?v=lyZQPjUT5B4
Consider this array: {40, 7, 59, 4, 1}
• Following the steps of the algorithm, after the first step of comparing and swapping the first
two values we have: {7, 40, 59, 4, 1}
• Then we compare and swap the next two values and get:
• Notice that the swap didn't occur in the second comparison. This is because they are already in
the correct order. {7, 40, 59, 4, 1}
• These steps are repeated until finally we get a sorted array: {1, 4, 7, 40, 59}