×

Sorting Algorithms

Sorting: In the data structure, sorting is the process by which you arrange the data in a logical order. This logical order can also be an ascending order or a descending order.

Sorting is related to searching. We search for many things in our life, such as a topic on google, a page in the book, a word in the dictionary, and roll number in the exam hall. Therefore, all these things that happen are sorted so that we can easily search them.

Types of sorting

There are two types of sorting in the data structure:

  1. Internal sorting
  2. External sorting

Internal sorting: The data to be sorted in this sorting resides in the main memory. There are the following types of internal sorting.

  1. Bubble sort
  2. Insertion sort
  3. Quick sort
  4. Heap sort
  5. Selection sort

External sorting: The data to be sorted in this sorting resides in secondary memory. There is so much data in this sorting that it cannot enter the main memory. There is only one type of external sorting called merge sort.

Bubble sort

Bubble sort is a very easy sorting technique. It compares all the elements one by one. It sorts them based on their values. In this, the two elements of the beginning are compared. If the first element is larger than the second element, it will change both elements' location, and this comparison will go on till the end.

Complexity table of bubble sort

ComplexityBest caseAverage caseWorst case
TimeO(n)O(n2)O(n2)
Space  O(1)

Algorithm of bubble sort

The following algorithm is used to implement a bubble sort.

Bubble_Sort(A)
Step 1: Repeat Step 2 and 3 for i = 1, 2….to n-1
Step 2: set j = 1
Step 3: Repeat while (j < n - i)              
{                
if (A[j] > A[j + 1])                 swap A[j] and A[j + 1]                 j = j + 1              
}
// end of while loop                  
// end of for loop    
Step 4: exit

For example: Let’s consider an array A{8. 14, 6, 7, 32, 15}.

  8 14 6 7 32 15  

First iteration
Step 1: Compare the first two elements, 8 < 14.             
No interchange
8 14 6 7 32 15  
Step 2: Compare the second and third elements, 14 > 6.            
The second element is larger than the third element, so it will swap the elements.       
8 6 14 7 32 15  
Step 3: Compare the third and fourth elements, 14 > 7.            
The third element is larger than the fourth element, so it will swap the elements.     
8 6 7 14 32 15  
Step 4: Compare the fourth and fifth elements, 14 < 32.             
No interchange  
8 6 14 7 32 15  
Step 5: Compare the fifth and sixth elements, 32 > 15.                                     
The fifth element is larger than the sixth element, so it will swap the elements.  
8 6 14 7 15 32                     
The first iteration is completed. Similarly, all iterations will be performed.  

Bubble sort program in C language.

#include<stdio.h>
 void main ()
   {      
 int i, j,temp;       
 int a[10] = {8, 7, 9, 1, 3, 2, 5, 10, 6, 4};        
for(i = 0; i<10; i++)       
{         
  for(j = i+1; j<10; j++) 
          {              
 if(a[j] > a[i])               
{                  
temp = a[i];                  
a[i] = a[j];                  
a[j] = temp;                 
}          
   }        
}   
printf("Bubble sort list\n"); 
  for(i = 0; i<10; i++) 
  {   printf("%d\n",a[i]);   }
        }    

Output:

Bubble sort list
1
2
3
4
5
6
7
8
9
10

Bubble sort program in java language

class BubbleSort
{            
void bubbleSort(int arr[])            
{                       
  int n = arr.length;                        
for (int i = 0; i < n-1; i++)                                   
  for (int j = 0; j < n-i-1; j++)                                                
if (arr[j] > arr[j+1])                                                
{          // swap arr[j+1] and arr[i]                  
  int temp = arr[j];                                                            
arr[j] = arr[j+1];                                                            
arr[j+1] = temp;                                                
}            
}               /* Prints the array */            
void printArray(int arr[])            
{                         int n = arr.length;                        
for (int i=0; i<n; ++i)                                   
System.out.print(arr[i] + " ");                      
   System.out.println();            
}               // Driver method to test above            
public static void main(String args[])            
{                        
BubbleSort ob = new BubbleSort();                        
int arr[] = {8, 7, 9, 1, 3, 2, 5, 10, 6, 4};                       
  ob.bubbleSort(arr);                  
       System.out.println("Bubble sort list");                       
  ob.printArray(arr);             } }  

Output:

Bubble sort list
1
2
3
4
5
6
7
8
9
10

Related Topics

Lowest Common Ancestor in a Binary Tree

The lowest node in the tree that contains both n1 and n2 as descendants is the lowest common ancestor (LCA), and n1 and n2 are the nodes for which we...

11 minutes read.

Graph Data Structure

A graph is a non-primitive and non-linear data structure. It is a group of (V, E) where V is a set of vertexes, and E is a set of edge....

3 minutes read.

Finding the Sum of All Paths in a Binary Tree

Implementation // Writing the C++ program to implement the below approach.  #include <bits/stdc++.h> using namespace std; // creating the new tree node structure. struct Tree__nod { int val; Tree__nod *Lft, *Rt; }; // creating a new function that will...

8 minutes read.

Stack vs Array

Difference between Array and Stack In this article, we are going to discuss the major differences between the stack and array data structures: Array – In the data structure, the array is...

3 minutes read.

Dynamic memory allocation of structure in C

We can normally store elements of the same datatype with the help of an array in C programming. We can store multiple numbers of elements of a character data type...

5 minutes read.

Top view of binary tree

We know that a binary tree is a kind of tree that helps us organize our tree and that it is a kind of non-linear info structure that at least...

4 minutes read.

Operations of B Tree in C++ Language

B tree tends to be a self-aligning and balancing tree that helps us organise our data and document safely. We know that every data or information in the B tree...

9 minutes read.

Remove duplicates from an unsorted Linked List

Remove duplicates from an unsorted Linked List This article will explain how we can remove duplicates from unsorted linked lists. Here we have given an unsorted singly linked list and will...

3 minutes read.

Finding the Maximum Element in a Binary Tree

Implementation // Creating a C++ program to excavate the minimum and maximum in a given binary tree. #include <bits/stdc++.h> #include <iostream> using namespace std; // creating a new tree node. class __nod { public: int record; __nod *Lft, *Rt; /*...

4 minutes read.

LCA of binary tree

Implementation //Writing a program to find the lowest common factor in a given binary search tree. #include <iostream> #include <vector> using namespace std; // the very first step is to create a binary tree. struct __nod { int...

8 minutes read.

Operations on 1D-Arrays

One Dimensional Array Operations Basic Methods The fundamental operations enabled by an array are listed below. Traverse prints each element of the array one by one.Insert a new element at the specified index.Delete...

8 minutes read.

Perfect Binary Tree

Complete binary trees are an important and general topic in the concept – of tree data structures. Before discussing a complete binary tree, we need to know the concept of...

4 minutes read.

Diameter of a Binary Tree

Implementation We will now witness the implementation of the diameter of a binary tree. // Creating a recursive and challenging C program that will help us determine the diameter of a binary...

4 minutes read.

Linear Search

Searching: In the data structure, searching is the process in which an element is searched in a list that satisfies one or more than one condition. Types of searching There are two...

4 minutes read.

Difference between complete and full binary tree

As we all know that the  binary tree is a tree it contains one or two children at each other node. It contains two children's nodes in the Binary tree. The...

6 minutes read.

Heap Sort in Data Structure

Heap Sort A heap is a tree-based data structure that has specific properties. Heap is always a complete binary tree (CBT). That is, all the nodes of the tree are completely filled.If...

6 minutes read.

Right side view of binary tree

The right view of the binary tree is generally known to be that side viewed from the right direction of the point of view. To be more precise, the right-side...

8 minutes read.

Given a Binary Tree Check the Zig-Zag Traversal

Implementation // The C++ implementation of the zig-zag traversal method in the O(n) time.  #include <iostream> #include <stack> using namespace std; // creating a binary tree node. struct __nod { int record; struct __nod *Lft, *Rt; }; // creating a...

4 minutes read.

What is a full Binary Tree?

A full binary tree is considered to be a special kind of binary tree in which every single node or leaf node present either contains two children or no children...

4 minutes read.

Find all possible words from board

We have been given a dictionary of words and a board of characters from which we can form strings. Now, we have to check if the string is present in...

5 minutes read.