Sorting in Data Structure: Categories & Types [With Examples]

The arrangement of data in a preferred order is called sorting in the data structure. By sorting data, it is easier to search through it quickly and easily. The simplest example of sorting is a dictionary. Before the era of the Internet, when you wanted to look up a word in a dictionary, you would do so in alphabetical order. This made it easy.

Imagine the panic if you had to go through a big book with all the English words from the world in a jumbled order! It is the same panic an engineer will go through if their data is not sorted and structured. 

So, in short, sorting makes our lives easier.

In this post, we will take you through the different data structures & sorting algorithms. But first, let’s understand what a sorting algorithm is.

What is a Sorting Algorithm?

A sorting algorithm is just a series of orders or instructions. In this, an array is an input, on which the sorting algorithm performs operations to give out a sorted array.

Many children would have learned to sort in data structures in their computer science classes. It is introduced at an early stage to help interested children get an idea of deeper computer science topics – divide-and-conquer methods, binary trees, heaps, etc.

Here’s an example of what sorting does.

Let’s suppose you have an array of strings: [h,j,k,i,n,m,o,l]

Now, sorting would yield an output array in alphabetical order.

Output: [h,i,j,k,l,m,n,o]

Sorting Categories

There are two different categories in sorting:

  • Internal sorting: If the input data is such that it can be adjusted in the main memory at once, it is called internal sorting.
  • External sorting: If the input data is such that it cannot be adjusted in the memory entirely at once, it needs to be stored in a hard disk, floppy disk, or any other storage device. This is called external sorting.

Read: Interesting Data Structure Project Ideas and Topics

Types of Sorting in Data Structure

Here are a few of the most common types of sorting algorithms.

1. Merge Sort

This algorithm works on splitting an array into two halves of comparable sizes. Each half is then sorted and merged back together by using the merge () function.

Here’s how the algorithm works:

MergeSort(arr[], l,  r)

If r > l

  1. Divide the array into two equal halves by locating the middle point:  

             middle m = (l+r)/2

  1. Use the mergeSort function to call for the first half:   

             Call mergeSort(arr, l, m)

  1. Call mergeSort for the second half:

             Call mergeSort(arr, m+1, r)

  1. Use the merge () function to merge the two halves sorted in step 2 and 3:

             Call merge(arr, l, m, r)

Check out the image below to get a clear picture of how this works.

Source

Python program for merge sort implementation

def mergeSort(a): 

    if len(a) >1: 

        mid = len(a)//2

        A = a[:mid]   

        B = a[mid:]

        mergeSort(A) 

        mergeSort(B) 

        i = j = k = 0    

        while i < len(A) and j < len(B): 

            if A[i] < B[j]: 

                a[k] = A[i] 

                i+=1

            else: 

                a[k] = B[j] 

                j+=1

            k+=1

        while i < len(A): 

            a[k] = A[i] 

            i+=1

            k+=1       

        while j < len(R): 

            a[k] = B[j] 

            j+=1

            k+=1 

def printList(a): 

    for i in range(len(a)):         

        print(a[i],end=” “) 

    print() 

if __name__ == ‘__main__’: 

    a = [12, 11, 13, 5, 6, 7]   

    mergeSort(a) 

    print(“Sorted array is: “, end=”\n”) 

    printList(a) 

Learn more: Recursion in Data Structure: How Does it Work, Types & When Used

2. Selection Sort

In this, at first, the smallest element is sent to the first position.

Then, the next smallest element is searched in the remaining array and is placed at the second position. This goes on until the algorithm reaches the final element and places it in the right position. 

Look at the picture below to understand it better.

 Source

Python program for selection sort implementation

import sys 

X = [6, 25, 10, 28, 11] 

for i in range(len(X)): 

        min_idx = i 

    for j in range(i+1, len(X)): 

        if X[min_idx] > X[j]: 

            min_idx = j 

    X[i], X[min_idx] = X[min_idx], X[i]  

print (“The sorted array is”) 

for i in range(len(X)): 

    print(“%d” %X[i]),  

Check out: Java Developer Salary in India: For Freshers & Experienced

3. Bubble Sort

It is the easiest and simplest of all the sorting algorithms. It works on the principle of repeatedly swapping adjacent elements in case they are not in the right order.

In simpler terms, if the input is to be sorted in ascending order, the bubble sort will first compare the first two elements in the array. In case the second one is smaller than the first, it will swap the two, and move on to the next element, and so on.

Example:

Input: 637124

First pass

637124 -> 367124 : Bubble sort compares 6 and 3 and swaps them because 3<6.

367124 -> 367124 : Since 6<7, no swapping

367124 -> 361724 : Swapped 7and 1, as 7>1

361724 -> 361274 : Swapped 2 and 7, as 2<7

361274 -> 361247 : Swapped 4 and 7, as 4<7

Second pass

361247 -> 361247

361274 -> 316274

316274 -> 312674

312674 -> 312674

312674 -> 312647

Third pass

312647 -> 132647

132647 -> 123647

123647 -> 123647

123647 -> 123467

123467 -> 123467

As you can see, we get the ascending order result after three passes.

Python program for bubble sort implementation

def bubbleSort(a): 

    n = len(a) 

    for i in range(n): 

        for j in range(0, n-i-1): 

            if a[j] > a[j+1] : 

                a[j], a[j+1] = a[j+1], a[j]  

a = [64, 34, 25, 12, 22, 11, 90] 

bubbleSort(a) 

print (“The sorted array is:”) 

for i in range(len(a)): 

    print (“%d” %a[i]), 

Also read: Data Frames in Python: Python In-depth Tutorial

Conclusion

That wraps up sorting in data structure and the most common sorting algorithms. You can choose any of the different types of sorting algorithms. However, remember that some of these can be a little tedious to write the program for. But then, they might come in handy for quick results. On the other hand, if you want to sort large datasets, you must choose the bubble sort. Not only does it yield accurate results, but is also easy to implement. Then again, it is slower than the other types.

To gain more insights into how sorting works, reach out to us and we will help you get started on the course that best suits your needs!

If you are curious to learn about data science, check out IIIT-B & upGrad’s PG Diploma in Data Science which is created for working professionals and offers 10+ case studies & projects, practical hands-on workshops, mentorship with industry experts, 1-on-1 with industry mentors, 400+ hours of learning and job assistance with top firms.

Have fun coding!

Prepare for a Career of the Future

UPGRAD AND IIIT-BANGALORE'S PG DIPLOMA IN DATA SCIENCE
Apply Now

Leave a comment

Your email address will not be published. Required fields are marked *

×