How to Write a Sorting Algorithm

How to Write a Sorting Algorithm#

sorting_img

In the fundamental of algorithm, there are many a basic algorithms are applied to computational process, one of them is a sort list of data either from minimum to maximum (ascending) or maximum to minimum (descending). Have you wondering how does it can be done? Here is the algorithm explanation.

Suppose we have a list of data such as data=(3,2,6,0). We want to sort this data from minimum to maximum by using a computer code through an algorithm. Of course, this is very simple data if we sort manually without a computer code. How about we have a lot of data like a thousand or more? Do we want to sort it manually? Of course we don’t. In manual way sort ascendinglly, we know that the data will be data=(0,2,3,6). There are some processes can be done by using computer code or algorithm. I will apply the algorithm by using Python 3.

Here are the points of process that you should be noticed:

  1. Identifying a number of data (n)

  2. Iterating all of data (i)

  3. Applying nest-iterating (j) from the first data (0) to the end of data. The end of data is based on the n-i-1. The -1 is used because the index of first data is started from 0.

  4. If the first data greater than with the next data, data(j)>data(j+1), then the list of data will be updated as data(j)=data(j+1) and data(j+1)=data(j). This is called swap process.

  5. This process will be continued until all iterations has been completed.

Here is the Python code of sort algorithm written as a function of sort

[1]:
# SORTED VALUES, MINIMUM TO MAXIMUM

data = [3,2,6,0]

def sort(arr, ascending=True):
    n = len(arr)
    for i in range(n):
        # Iterate through the list up to the unsorted part
        for j in range(0, n-i-1):
          if ascending == True:
            # Swap if the current element is greater than the next (ascending)
            if arr[j] > arr[j+1]:
              arr[j], arr[j+1] = arr[j+1], arr[j]
          else:
            # Swap if the current element is lower than the next (descending)
            if arr[j] < arr[j+1]:
              arr[j], arr[j+1] = arr[j+1], arr[j]

    return arr

# Example usage:
sorted_list_ascending = sort(data, ascending=True)
print("Sorted List (Min to Max):", sorted_list_ascending)
sorted_list_descending = sort(data, ascending=False)
print("Sorted List (Max to Min):", sorted_list_descending)
Sorted List (Min to Max): [0, 2, 3, 6]
Sorted List (Max to Min): [6, 3, 2, 0]

The output will be

# Output
Sorted List (Min to Max): [0, 2, 3, 6]
Sorted List (Max to Min): [6, 3, 2, 0]

The function sort is requested variable of ascending. This variabel is default to True, which means the data will be sorted from minimum to maximum. You can assign the value equal to False to give the sorted data from maximum to minimum.