Introduction to Sorting in DAA

DAA: What is Sorting?

The technique in which a data structure is rearranged in decreasing order, increasing order, or in a specified order is called sorting.

We apply to sort in our day-to-day lives in various ways. In real life, sorting is seen in:

  1.  Ranking based on scores
  2.  People standing in a queue according to their heights
  3.  A dictionary or telephone directory in which words are sorted alphabetically.

In technical terms, the concept of sorting is applied to linear data structures such as Arrays, LinkedList, Stack, Queues, and many more.

Applications of Sorting

Some important applications of sorting are as follows:

  1. Efficiently search an item: When all the items will be arranged in an order, it is easy to search for an item.
  2. Commercial computing: Industrial and governmental organizations use enhanced sorting-based techniques to manage their databases. It becomes easier to sort the data according to time, place, date, identity number, etc.
  3. String processing: String algorithms are mostly based on sorting. We can arrange a string in order of their ASCII values.
  4.  Numerical computations: Numerical computations focus on approximate close answers to a given problem statement. The priority queue uses various sorting algorithms to get accurate results.

Sorting Algorithms

When we write a sorting algorithm, efficiency and time complexity are the two major points to be kept in mind. The algorithm should work correctly and should have less execution time. A programmer uses the correct algorithm to escape from the TLE( time limit exceeded) issue. On this note, the various sorting algorithms are listed below -

  1. Selection sort
  2. Bubble sort
  3. Insertion sort
  4. Merge sort
  5. Heapsort
  6. Quicksort
  7. Radix sort
  8. Shell sort
  9. Counting sort
  10. Comb sort

Now let us discuss each sorting algorithm in detail -

DAA SELECTION SORT

The algorithm is a comparison-based in-place algorithm in which the array is divided into two parts as:

  1. The sorted part at the left end.
  2. The unsorted part at the right end.

Initially, the unsorted part is the entire array, and the sorted part is zero as we had not sorted our array.

Algorithm:

Select the smallest element from the unsorted part and swap with the leftmost element, and that element becomes a part of the sorted array. This process repeats for n iterations till the whole array is sorted.

Time complexity

O(n^2)  as there are two nested loops.

Space complexity

 O(1). 

C++ Code:

 #include <bits/stdc++.h>
 using namespace std;
 void swap(int *xp, int *yp)
 {
          int temp = *xp;
          *xp = *yp;
          *yp = temp;
 }
 void selectionSort(int arr[], int n)
 {
          int i, j, min_idx;
           for (i = 0; i < n-1; i++)  // Iterate through the entire array
          {
                       min_idx = i;
                    for (j = i+1; j < n; j++)     /* From the unsorted part
                     minimal element is found*/
                    if (arr[j] < arr[min_idx])
                             min_idx = j;
          // Swap minimum element from unsorted part and first element
                    swap(&arr[min_idx], &arr[i]);
          }
 }
 // This function prints the array
 void printArray(int arr[], int size)
 {
          int i;
          for (i=0; i < size; i++)
                    cout << arr[i] << " ";
          cout << endl;
 }
 int main()
 {
          int arr[] = {64, 25, 12, 22, 11};
          int n = 5;
          selectionSort(arr, n);
          cout << "Sorted array: \n";
          printArray(arr, n);
          return 0;
 } 

C code:

 #include <stdio.h>
 void swap(int *xp, int *yp)
 {
          int temp = *xp;
          *xp = *yp;
          *yp = temp;
 }
 void selectionSort(int arr[], int n)
 {
          int i, j, min_idx;
          for (i = 0; i < n-1; i++) // One by one move boundary of unsorted subarray
          {
                    // From the unsorted section find minimum element
                    min_idx = i;
                    for (j = i+1; j < n; j++) //Iterate through inner loop to compare
                    if (arr[j] < arr[min_idx])
                             min_idx = j;
                                       swap(&arr[min_idx], &arr[i]);
          }
 }
 void printArray(int arr[], int size)
 {
          int i;
          for (i=0; i < size; i++)
                    printf("%d ", arr[i]);
          printf("\n");
 }
 int main()
 {
          int arr[] = {64, 25, 12, 22, 11};
          int n = 5;
          selectionSort(arr, n);
          printf("Sorted array: \n");
          printArray(arr, n);
          return 0;
 } 

Java code:

 class SelectionSort
 {
          void sort(int arr[])
          {
                    int n = arr.length;
          for (int i = 0; i < n-1; i++)
                    {
                             int min_idx = i;
                             for (int j = i+1; j < n; j++)
                                       if (arr[j] < arr[min_idx])
                                                min_idx = j;
          // Swap minimum element from unsorted part and first element
                             int temp = arr[min_idx];
                             arr[min_idx] = arr[i];
                             arr[i] = temp;
                    }
          }
           void printArray(int arr[])
          {
                    int n = arr.length;
                    for (int i=0; i<n; ++i)
                             System.out.print(arr[i]+" ");
                    System.out.println();
          }
                    public static void main(String args[])
          {
                    SelectionSort ob = new SelectionSort();
                    int arr[] = {64,25,12,22,11};
                    ob.sort(arr);
                    System.out.println("Sorted array");
                    ob.printArray(arr);
          }
 } 

Related Topics

DAA: Continuous Tree

Continuous Tree A continuous tree is the one in which the nodes from root to leaf path, the two adjacent node values, have a difference of 1. Input :          3                     /   \                   ...

5 minutes read.

DAA: Application of DFS and BFS

Application of DFS and BFS Depth-first search and breadth-first searches are the most famous algorithms used in daily life and the programming world. Let us now explore each application in which...

3 minutes read.

Segregate the given Linked List in DAA

Segregate Even and Odd Nodes in a Linked List A linked list is a linear data structure in which each node has two blocks. One contains the node’s value or data,...

3 minutes read.

DAA: Rabin Karp Algorithm

Rabin Karp Algorithm The Rabin Karp or Karp Rabin algorithm is used to matching a specific pattern in the string. It uses the technique of hashing to match a specific text. There also...

6 minutes read.

Introduction to Sorting in DAA

DAA: What is Sorting? The technique in which a data structure is rearranged in decreasing order, increasing order, or in a specified order is called sorting. We apply to sort in our...

4 minutes read.

Invert Binary Tree in DAA

Invert Binary Tree: A binary tree is a tree in which each node of the tree contains two children, i.e., left children and right children. Let us suppose we have...

2 minutes read.

DAA: KMP Algorithm

KMP ALGORITHM The KMP algorithm is abbreviated as the "Knuth Morris Pratt” algorithm. This algorithm was developed by all of them.  This algorithm searches a pattern of length m in a string...

10 minutes read.

Recurrence relation in DAA

Recurrence relation in DAA The model that uses mathematical concepts to calculate the time complexity of an algorithm is known as the recurrence relational model. A recursive relation, T(n), is a recursive...

5 minutes read.

DAA: Depth-First Search Algorithm

Depth-first search: DFS is a traversing algorithm of a graph or tree in which one node is taken as arbitrary, and with the help of that arbitrary node, all its...

6 minutes read.

DAA: Find the Height or Maximum Depth of a Binary Tree

Find the Height or Maximum Depth of a Binary Tree We have a binary tree structure and we need to find its height. It is defined by the distance from the...

3 minutes read.

DAA: Dijkstra’s Algorithm (Shortest Path)

Dijkstra’s Algorithm (Shortest Path) Dijkstra’s algorithm finds the shortest distance from a source to all the vertices in a graph. This algorithm is used in network protocols like IS-IS and OSPF(Open...

3 minutes read.

DAA: Euclid Algorithm

Euclid Algorithm The Euclid algorithm finds the GCD of two numbers in the efficient time complexity. To find the GCD of two numbers, we take the two numbers’ common factors and multiply...

8 minutes read.

DAA: Bubble Sort Algorithm on Linked List

Bubble Sort Algorithm on Linked List In this article, we will sort a Link List using the bubble sort technique. Example: Input : 20->30->40->10 Output :10->20->30->40 Input : 20->4->3 Output : 3->4->20 Sorting Technique The bubble sort technique...

4 minutes read.

DAA: Interpolation Search Algorithm

Interpolation Search Algorithm There is no doubt that binary search is a great algorithm with average time complexity of log n. The feature of discarding one half of the array reduces...

4 minutes read.

DAA: Algorithm of Right View of a Binary Tree

Algorithm of Right View of a Binary Tree The right view of a binary tree is the visible nodes from the right side of the tree. In the given tree, the visible...

5 minutes read.

DAA: Insert a node in Binary Search Tree

Insert a node in Binary Search Tree (BST) We have a Binary search tree and a key. Insert the key in the binary search tree if not present. In the above figure,...

4 minutes read.

DAA: Binary Tree and its Categories

Binary Tree and its Categories The binary tree is a non-linear data structure in which there are 0 or utmost 2 nodes.  Each node has two children, i.e., left and right...

4 minutes read.

Symmetric Trees in DAA

Symmetric Trees The trees that are mirror images of themselves are known as symmetric trees. Look at the following tree image below: The tree is symmetric as the left subtree is the mirror...

4 minutes read.

DAA: Bead Sort Algorithm

Bead Sort Algorithm The bead sort is also known as the gravity sort algorithm. The algorithm is based on the natural phenomena of gravity. The phenomenon is the falling of things...

3 minutes read.

DAA: Expression Trees

Expression Trees Expression trees are those in which the leaf nodes have the values to be operated, and internal nodes contain the operator on which the leaf node will be performed. Example:...

4 minutes read.