Sorting and Its types with Examples
Sorting is a method of arranging data in either increasing order or decreasing order. Several sorting algorithms are purposed. Sorting algorithm specifies the way to arrange data in a particular order. Most common orders are numerical or lexicographical order. Some of the well-known are as follows:
Insertion Sort:
In this method an element is selected from the list of elements,
that element is inserted into its correct position by shifting other elements
if necessary. The selection of elements is done one by one and are placed in
their correct position. The time complexity of this algorithm is O(n2)
We
can create a java program to sort array elements using insertion sort.
Insertion is good for small elements only because it requires more time for
sorting large number of elements.
public class InsertionSortExample {Â Â
  public static void insertionSort(int array[]) { Â
    int n = array.length; Â
    for (int j = 1; j < n; j++) { Â
      int key = array[j]; Â
      int i = j-1; Â
      while ( (i > -1) && ( array [i] > key ) ) { Â
        array [i+1] = array [i]; Â
        i--; Â
      } Â
      array[i+1] = key; Â
    } Â
  }   Â
  public static void main(String a[]){  Â
    int[] arr1 = {9,14,3,2,43,11,58,22};  Â
    System.out.println("Before Insertion Sort");  Â
    for(int i:arr1){  Â
      System.out.print(i+" ");  Â
    }  Â
    System.out.println();  Â
      Â
    insertionSort(arr1);//sorting array using insertion sort  Â
     Â
    System.out.println("After Insertion Sort");  Â
    for(int i:arr1){  Â
      System.out.print(i+" ");  Â
    }  Â
  }  Â
}Â Â Â
Output:
Before Insertion Sort
9 14 3 2 43 11 58 22Â
After Insertion Sort
2 3 9 11 14 22 43 58Â
Selection Sort:
An maximum element is selected from the list of size n, that
maximum element is swapped with the last element of the list of size n. Then
second maximum element is selected from the list of size n-1, that second
maximum element is swapped with last element of the list of size n-1. This
selection of maximum element and swapping it with last element of the list of
decreasing size continues until all the elements are selected and placed in
their correct position. The time complexity of this algorithm is O(n2)
We can create a java program to sort array elements using
selection sort. In selection sort algorithm, we search for the lowest element
and arrange it to the proper location. We swap the current element with the
next lowest number.
How does selection
sort work?
The selection sort algorithm works in a very simple way. It
maintains two subarray for the given array.
- ·      The subarray is already sorted.
- ·      And the second subarray is unsorted.
With every iteration of selection sort, an element is picked
from the unsorted subarray and moved to the sorted subarray.
Selection Sort Java Example:
public class SelectionSortExample {Â
   public static void
selectionSort(int[] arr){Â
       for (int i = 0; i
< arr.length - 1; i++)Â
       {Â
           int index =
i;Â
           for (int j = i
+ 1; j < arr.length; j++){Â
               if (arr[j]
< arr[index]){Â
                   index
= j;//searching for lowest indexÂ
               }Â
           }Â
           int
smallerNumber = arr[index];Â Â
           arr[index] =
arr[i];Â
           arr[i] =
smallerNumber;Â
       }Â
   }Â
   public static void
main(String a[]){Â
       int[] arr1 =
{9,14,3,2,43,11,58,22};Â
      Â
System.out.println("Before Selection Sort");Â
       for(int
i:arr1){Â
          Â
System.out.print(i+" ");Â
       }Â
       System.out.println();Â
       selectionSort(arr1);//sorting array using selection sortÂ
      Â
System.out.println("After Selection Sort");Â
       for(int
i:arr1){Â
          Â
System.out.print(i+" ");Â
       }Â
   }Â
}Â
Output:
Before Selection Sort
9 14 3 2 43 11 58 22
After Selection Sort
2 3 9 11 14 22 43 58
MergeSort:
MergeSort is based on divide and conquer algorithm. A array or
list of size n is divided until n lists with one element is formed. Then those
individual n lists are merged. First from n lists, two consecutive lists are
considered, merged and sorted to form n/2 lists with two elements. Then two
lists of two elements are merged and sorted to form total n/4 lists. This
process will continue until one single sorted list is formed. The time
complexity of this algorithm is O(nlogn)
Working of Merge sort Algorithm
Now, let's see the working of merge sort Algorithm.
To understand the working of the merge sort algorithm, let's
take an unsorted array. It will be easier to understand the merge sort via an
example.
Let the elements of array are -
According to the merge sort, first divide the given array into
two equal halves. Merge sort keeps dividing the list into equal parts until it
cannot be further divided.
As there are eight elements in the given array, so it is divided
into two arrays of size 4.
Write a program to implement merge sort in Java.
class Merge {Â
/* Function to merge the subarrays of a[] */Â
void merge(int a[], int beg, int mid, int end)Â Â Â
{Â Â Â
   int i, j, k;Â
   int n1 = mid - beg +
1;Â Â Â
   int n2 = end -
mid;Â Â Â
    Â
  /* temporary Arrays
*/Â
       int LeftArray[] =
new int[n1];Â
       int RightArray[] = new int[n2];Â
   /* copy data to temp
arrays */Â
   for (i = 0; i < n1;
i++)Â Â Â
   LeftArray[i] = a[beg +
i];Â Â Â
   for (j = 0; j < n2;
j++)Â Â Â
   RightArray[j] = a[mid
+ 1 + j];Â Â Â
   i = 0; /* initial
index of first sub-array */Â
   j = 0; /* initial
index of second sub-array */Â Â
   k = beg; /* initial index of merged sub-array */Â
   while (i < n1
&& j < n2)Â Â Â
   {  Â
       if(LeftArray[i]
<= RightArray[j])Â Â Â
       {  Â
           a[k] =
LeftArray[i];Â Â Â
           i++;  Â
       }  Â
       else  Â
       {  Â
           a[k] =
RightArray[j];Â Â Â
           j++;  Â
       }  Â
       k++;  Â
   }  Â
   while (i<n1)  Â
   {  Â
       a[k] = LeftArray[i];  Â
       i++;  Â
       k++;  Â
   } Â
   while (j<n2)  Â
   {  Â
       a[k] =
RightArray[j];Â Â Â
       j++;  Â
       k++;  Â
   }  Â
}Â Â
void mergeSort(int a[], int beg, int end)Â
{Â
   if (beg < end) Â
   {Â
       int mid = (beg +
end) / 2;Â
       mergeSort(a, beg,
mid);Â
       mergeSort(a, mid +
1, end);Â
       merge(a, beg, mid,
end);Â
   }Â
}Â
/* Function to print the array */Â
void printArray(int a[], int n)Â
{Â
   int i;Â
   for (i = 0; i < n;
i++)Â
      Â
System.out.print(a[i] + " ");Â
}Â
public static void main(String args[])Â
{Â
   int a[] = { 11, 30,
24, 7, 31, 16, 39, 41 };Â
   int n = a.length;Â
   Merge m1 = new
Merge();Â
   System.out.println("\nBefore
sorting array elements are - ");Â
   m1.printArray(a,
n);Â
   m1.mergeSort(a, 0, n -
1);Â
  Â
System.out.println("\nAfter sorting array elements are -
");Â
   m1.printArray(a,
n);Â
  Â
System.out.println("");Â
}Â
 }Â
Output:
Before sorting array elements are -
11 30 24 7 31 16 39 41
After sorting array elements are -
7 11 16 24 30 31 39 41
Quick Sort:
Quicksort is based on the concept of divide and conquer
algorithm. One of the element of a list of size n is considered as pivot,
elements smaller than that pivot is placed at the left side of the pivot,
elements greater than or equal to the pivot are placed at the right of the
pivot in the list. In this way two sublists are formed, one at the left of the
pivot, another at the right of the pivot. This selection of pivot, placing
smaller elements in the left of the pivot and greater or equal elements in the
right of the pivot is continued with all the formed sub-list. In this way list
is sorted. The time complexity of this algorithm is O(nlogn)
Write a program to implement quicksort in Java.
public class QuickÂ
{Â
   /* function that
consider last element as pivot,Â
place the pivot at its exact position, and placeÂ
smaller elements to left of pivot and greaterÂ
elements to right of pivot.Â
*/Â
int partition (int a[], int start, int end)Â
{Â
   int pivot = a[end]; //
pivot elementÂ
   int i = (start - 1);Â
Â
   for (int j = start; j
<= end - 1; j++)Â
   {Â
       // If current
element is smaller than the pivotÂ
       if (a[j] <
pivot)Â
       {Â
           i++; //
increment index of smaller elementÂ
           int t =
a[i];Â
           a[i] =
a[j];Â
           a[j] = t;Â
       }Â
   }Â
   int t = a[i+1];Â
   a[i+1] = a[end];Â
   a[end] = t;Â
   return (i + 1);Â
}Â
/* function to implement quick sort */Â
void quick(int a[], int start, int end) /* a[] = array to be
sorted, start = Starting index, end = Ending index */Â
{Â
   if (start <
end)Â
   {Â
       int p =
partition(a, start, end);Â //p is
partitioning indexÂ
       quick(a, start, p
- 1);Â
       quick(a, p + 1,
end);Â
   }Â
}Â
/* function to print an array */Â
void printArr(int a[], int n)Â
{Â
   int i;Â
   for (i = 0; i < n;
i++)Â
      Â
System.out.print(a[i] + " ");Â
}Â
   public static void
main(String[] args) {Â
   int a[] = { 13, 18,
27, 2, 19, 25 };Â
   int n = a.length;Â
  Â
System.out.println("\nBefore sorting array elements are -
");Â
   Quick q1 = new
Quick();Â
   q1.printArr(a,
n);Â
   q1.quick(a, 0, n -
1);Â
  Â
System.out.println("\nAfter sorting array elements are -
");Â
   q1.printArr(a,
n);Â
  Â
System.out.println();Â
   }Â
}Â
Output:
Before sorting array elements are -
13 18 27 2 19 25
After sorting array elements are -
2 13 18 19 25 27
Heap Sort:
The largest element of the list is determined and placed in the
end of the list. This is continued until all the elements are placed in their
correct position. Heap sort is better than selection sort, it uses a data
structure called heap (a binary tree). Heap tree is from with the list of the
data and element from the root are taken out and placed in the array, as,
element of heap tree is removed from the root of the heap, and the properties
of the heap is maintained with each element removal. The time complexity of this
algorithm is O(nlogn)
Heap sort basically recursively performs two main operations -
- Build a heap H, using the elements of array.
- Repeatedly delete the root element of the heap formed in 1st phase.
Before knowing more about the heap sort, let's first see a brief
description of Heap.
Write a program to implement heap sort in Java.
class HeapSort Â
{Â Â
/* function to heapify a subtree. Here 'i' is the Â
index of root node in array a[], and 'n' is the size of heap. */Â Â
static void heapify(int a[], int n, int i)Â Â
{Â Â
  int largest = i; // Initialize largest as root Â
  int left = 2 * i + 1; // left child Â
  int right = 2 * i + 2; // right child Â
  // If left child is larger than root Â
  if (left < n && a[left] > a[largest]) Â
    largest = left; Â
  // If right child is larger than root Â
  if (right < n && a[right] > a[largest]) Â
    largest = right; Â
  // If root is not largest Â
  if (largest != i) { Â
    // swap a[i] with a[largest] Â
    int temp = a[i]; Â
    a[i] = a[largest]; Â
    a[largest] = temp; Â
     Â
    heapify(a, n, largest); Â
  } Â
}Â Â
/*Function to implement the heap sort*/Â Â
static void heapSort(int a[], int n)Â Â
{Â Â
  for (int i = n / 2 - 1; i >= 0; i--) Â
    heapify(a, n, i); Â
 Â
  // One by one extract an element from heap Â
  for (int i = n - 1; i >= 0; i--) { Â
    /* Move current root element to end*/ Â
    // swap a[0] with a[i] Â
    int temp = a[0]; Â
    a[0] = a[i]; Â
    a[i] = temp; Â
     Â
    heapify(a, i, 0); Â
  } Â
}Â Â
/* function to print the array elements */Â Â
static void printArr(int a[], int n)Â Â
{Â Â
  for (int i = 0; i < n; ++i) Â
    System.out.print(a[i] + " "); Â
}Â Â
public static void main(String args[])Â Â
{Â Â
  int a[] = {45, 7, 20, 40, 25, 23, -2}; Â
  int n = a.length; Â
  System.out.print("Before sorting array elements are - \n"); Â
  printArr(a, n); Â
  heapSort(a, n); Â
  System.out.print("\nAfter sorting array elements are - \n"); Â
  printArr(a, n); Â
}Â Â
}Â Â
Output:
Before sorting array elements are -
45 7 20 40 25 23 -2
After sorting array elements are -
-2 7 20 23 25 40 45