DEV Community

Ty
Ty

Posted on

Sorts

Sorts, oh sorts. A simple function but multiple ways to do them. During my dicussion questions in Flatiron. We were introduce to sorts and how they visually worked in react. Which was super fascinating to learn and also, I wanted to know more about algorithms. So I dove head first into sorts. Let's start with the two easiest sorts! Selection sort and insertion sort.

    // One by one move boundary of unsorted subarray 
    int n = arr.length; 

    for (int i = 0; i < n-1; i++) 
    { 
        // Find the minimum element in unsorted array 
        int min_idx = i; 
        for (int j = i+1; j < n; j++) 
            if (arr[j] < arr[min_idx]) 
                min_idx = j; 

        // Swap the found minimum element with the first 
        // element 
        int temp = arr[min_idx]; 
        arr[min_idx] = arr[i]; 
        arr[i] = temp; 
    } 
Enter fullscreen mode Exit fullscreen mode

What a selection sort is that it grabs the lowest number and put it to the front. Example on the first iteration, it'll grab index 0 and go through all the numbers in the array to find the lowest. Then it'll swap the element to the front if there is a lower number within the array length.
EX - 3, 4, 1, 5
It'll start with 3 and check if 4 < 3, or 1 < 3. Once that is true, the 1 and 3 swap places to be 1, 4, 3, 5. This repeat's til the end of the loop.

Another sort i'll be talking about is insertion sort.

    int n = arr.length; 
    for (int i = 1; i < n; ++i) { 
        int key = arr[i]; 
        int j = i - 1; 

        /* Move elements of arr[0..i-1], that are 
           greater than key, to one position ahead 
           of their current position */
        while (j >= 0 && arr[j] > key) { 
            arr[j + 1] = arr[j]; 
            j = j - 1; 
        } 
        arr[j + 1] = key; 
    } 
Enter fullscreen mode Exit fullscreen mode

Basically insertion is backwards and how we would be doing if we played cards. It will check the current index and see if its lower than the previous index before. It will check and see if its greater then the number before and less than the number that comes after. If we have a card of 3 2 1 5. The first loop will stay the same. But on the 2nd loop, it'll check if 2 is less than 3. So it'll be changed to 2, 3, 1, 5. The same would happen to 1, it'll check if 1 is less than 3, and it is. But it'll check again if it is less than one, and it is as well. So the array would change to 1 2 3 5. Now it checks if 5 is less than 3, but it is not. So the element stays on the current index and the loop is done.

It is interesting to see on how sorts work and there are many more types of sorts out there such as bubble sort. It is great to know the difference of each sort and learn the algorithm!

Top comments (0)