Sorting (Bubble, Selection, Insertion, Shell, Quick)
Sorting (Bubble, Selection, Insertion, Shell, Quick)
Bubble sort
Bubble Sort is the simplest sorting algorithm that
works by repeatedly swapping the adjacent elements if
they are in wrong order.
Example:
First Pass:
( 5 1 4 2 8 ) –> ( 1 5 4 2 8 ), Here, algorithm compares
the first two elements, and swaps since 5 > 1.
( 1 5 4 2 8 ) –> ( 1 4 5 2 8 ), Swap since 5 > 4
( 1 4 5 2 8 ) –> ( 1 4 2 5 8 ), Swap since 5 > 2
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 ), Now, since these elements
are already in order (8 > 5), algorithm does not swap
them.
Bubble sort
Second Pass:
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 )
( 1 4 2 5 8 ) –> ( 1 2 4 5 8 ), Swap since 4 > 2
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
Now, the array is already sorted, but our algorithm
does not know if it is completed. The algorithm needs
one whole pass without any swap to know it is sorted.
Bubble sort
Third Pass:
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
Ex01
public class BubbleSort01 {
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;
}
}
Output:
/* Prints the array */
void printArray(int arr[]) { Sorted array
int n = arr.length; 12345789
for (int i=0; i<n; ++i)
System.out.print(arr[i] + " ");
System.out.println();
}
public static void main(String[] args) {
BubbleSort01 ob = new BubbleSort01();
int arr[] = {5, 3, 1, 9, 8, 2, 4,7};
ob.bubbleSort(arr);
System.out.println("Sorted array");
ob.printArray(arr);
}
Ex 01 - Illustration
Optimized Implementation
The above function always runs O(n^2) time even if
the array is sorted. It can be optimized by stopping the
algorithm if inner loop didn’t cause any swap.
Ex02
public class BubbleSort02 {
static void bubbleSort(int arr[], int n) {
int i, j, temp;
boolean swapped;
for (i = 0; i < n - 1; i++) {
swapped = false;
for (j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
// swap arr[j] and arr[j+1]
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
swapped = true;
}
}
if (swapped == false) {// IF no two elements were swapped by inner loop, then break
System.out.println("No elements swapped! break the loop now!");
System.out.printf("i=%d\n", i );
System.out.printf("j=%d\n", j );
break;
} }
}
static void printArray(int arr[], int size) {
int i; Output:
for (i = 0; i < size; i++)
System.out.print(arr[i] + " "); No elements swapped! break the
System.out.println(); loop now!
}
public static void main(String[] args) { i=4
int arr[] = { 5, 3, 1, 9, 8, 2, 4,7 }; j=3
int n = arr.length;
bubbleSort(arr, n); Sorted array:
System.out.println("Sorted array: "); 12345789
printArray(arr, n);
}
}
Selection Sort
Selection sort is a simple sorting algorithm. This
sorting algorithm is an in-place comparison-based
algorithm in which the list is divided into two parts,
the sorted part at the left end and the unsorted part at
the right end. Initially, the sorted part is empty and the
unsorted part is the entire list.
The smallest element is selected from the unsorted
array and swapped with the leftmost element, and that
element becomes a part of the sorted array. This
process continues moving unsorted array boundary by
one element to the right.
How Selection Sort Works?
The first position where 14 is
stored presently, we search
the whole list and find that 10
is the lowest value. So we
replace 14 with 10.
Next, We find that 14 is the
second lowest value in the list
and it should appear at the
second place. We swap these
values.
And so on.
Ex 03
public class SelectionSort {
void sort(int arr[]) {
int n = arr.length;
// One by one move boundary of unsorted subarray
for (int i = 0; i < n-1; i++) {
// Find the minimum element in unsorted array
int min_idx = i;
for (int j = i+1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;
// Swap the found minimum element with the first element
int temp = arr[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp;
}
}
void printArray(int arr[]) {
int n = arr.length; Output:
for (int i=0; i<n; ++i)
System.out.print(arr[i]+" "); Sorted array
System.out.println(); 11 12 22 25 64
}
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);
}
}
Insertion Sort
This is an in-place comparison-based sorting
algorithm. Here, a sub-list is maintained which is
always sorted. For example, the lower part of an array
is maintained to be sorted. An element which is to be
'insert'ed in this sorted sub-list, has to find its
appropriate place and then it has to be inserted there.
Hence the name, insertion sort.
Algorithm
insertionSort(arr, n)
Loop from i = 1 to n-1.
……a) Pick element arr[i] and insert it into sorted sequence arr[0…i-1]
How Insertion Sort Works?
Another Example
12, 11, 13, 5, 6
loop for i = 1 (2nd element of array) to 4 (last element of array)
i = 1. Since 11 is smaller than 12, move 12 and insert 11 before 12
11, 12, 13, 5, 6
i = 2. 13 will remain at its position as all elements in A[0..i-1] < 13
11, 12, 13, 5, 6
i = 3. 5 will move to the beginning and all other elements from 11 to 13
will move one position ahead of their current position.
5, 11, 12, 13, 6
i = 4. 6 will move to position after 5, and elements from 11 to 13 will
move one position ahead of their current position.
5, 6, 11, 12, 13
Ex 04
public class InsertionSort {
void sort(int arr[]) {
int n = arr.length;
for (int i = 1; i < n; ++i) {
int key = arr[i];
int j = i - 1;
/* Move elements of arr[0..i-1], that are
greater than key, to one position ahead
of their current position */
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
} Output:
static void printArray(int arr[]) { 5 6 11 12 13
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[]) {
int arr[] = { 12, 11, 13, 5, 6 };
InsertionSort ob = new InsertionSort();
ob.sort(arr);
printArray(arr);
}
Shell Sort
ShellSort is mainly a variation of Insertion Sort. In
insertion sort, we move elements only one position
ahead. When an element has to be moved far ahead,
many movements are involved. The idea of shellSort is
to allow exchange of far items. In shellSort, we make
the array h-sorted for a large value of h. We keep
reducing the value of h until it becomes 1. An array is
said to be h-sorted if all sublists of every h’th element
is sorted.
How Shell Sort Works?
How Shell Sort Works?
How Shell Sort Works?
How Shell Sort Works?
How Shell Sort Works?
How Shell Sort Works?
How Shell Sort Works?
1. For ease of understanding, we take the interval of 4.
Make a virtual sub-list of all values located at the
interval of 4 positions. Here these values are {35, 14},
{33, 19}, {42, 27} and {10, 44}