BogoToBogo
  • Home
  • About
  • Big Data
  • Machine Learning
  • AngularJS
  • Python
  • C++
  • go
  • DevOps
  • Kubernetes
  • Algorithms
  • More...
    • Qt 5
    • Linux
    • FFmpeg
    • Matlab
    • Django 1.8
    • Ruby On Rails
    • HTML5 & CSS

Algorithms - Insertion Sort





Bookmark and Share





bogotobogo.com site search:




Insertion Sort

Insertion sort is a very simple sorting algorithm that is relatively efficient for small lists and mostly-sorted lists.


It is often used as part of more sophisticated algorithms. It does sort by taking elements from the list one by one and inserting them in their correct position into a new sorted list. In arrays, the new list and the remaining elements can share the array's space, but insertion is expensive, requiring shifting all following elements over by one. The insertion sort works just like its name suggests - it inserts each item into its proper place in the final list.

  1. Insertion sort takes advantage of presorting.
    More efficient in practice than most other simple quadratic (O(n2)) algorithms such as selection sort or bubble sort
    the best case (nearly sorted input) is O(n).
  2. Efficient for small data sets.
  3. It requires fewer comparisons compared with bubble sort unless its list is backward.
    the time complexity is O(n + d), where d is the number of inversions.
  4. It requires only one comparison per element for a presorted list.
  5. It is stable sort. It does not change the relative order of elements with equal keys.
  6. It is in-place sorting. It only requires a constant amount O(1) of additional memory space.
  7. It is online sorting. It can sort a list as it receives it.
  8. With a sorted array, we can insert new elements.
  9. It is similar to the way we sort card deck.

The simplest implementation of this requires two list structures - the source list and the list into which sorted items are inserted. To save memory, most implementations use an in-place sort that works by moving the current item past the already sorted items and repeatedly swapping it with the preceding item until it is in place.

Shell sort is a variant of insertion sort that is more efficient for larger lists. This method is much more efficient than the bubble sort, though it has more constraints.

Psedo code should look like this:

   for i = 1, n
   j = i
   while(j > 0 and E[j] < E[j-1])
       swap(E[j], E[j-1])
       j--


C++ code

#include <iostream>
#include <iomanip>

using namespace std;

void swap(int &x;, int &y;)
{
	int temp = x;
	x = y;
	y = temp;
}

void insertion(int a[], int sz)
{
	for(int i=1; i  < sz; i++) {
		int j = i;
		while(j > 0 && (a[j] < a[j-1])) {
			swap(a[j], a[j-1]);
			j--;
		}
		cout << endl;
		for (int k = 0; k < sz; k++) cout << setw(3) << a[k];
	}
}

int main()
{
	int a[] = { 15, 9, 8, 1, 4, 11, 7, 12, 13, 6, 5, 3, 16, 2, 10, 14};
	int size = sizeof(a)/sizeof(int);
	for (int i = 0; i < size; i++) cout << setw(3) << a[i];
	insertion(a, size);
	cout << endl;
	return 0;
}

This is the way we're sorting cards.
Start by picking up a single card to form a hand that is already sorted. For each card picked up, find the right place to insert card into the hand, thus maintaining the invariant that the cards in the hand are sorted. When we hold cards in our hand, it is easy to insert a card into its correct position because the other cards are just pushed aside a bit to accept the new card.


Output from the run:

 15  9  8  1  4 11  7 12 13  6  5  3 16  2 10 14 
9 15 8 1 4 11 7 12 13 6 5 3 16 2 10 14
8 9 15 1 4 11 7 12 13 6 5 3 16 2 10 14
1 8 9 15 4 11 7 12 13 6 5 3 16 2 10 14
1 4 8 9 15 11 7 12 13 6 5 3 16 2 10 14
1 4 8 9 11 15 7 12 13 6 5 3 16 2 10 14
1 4 7 8 9 11 15 12 13 6 5 3 16 2 10 14
1 4 7 8 9 11 12 15 13 6 5 3 16 2 10 14
1 4 7 8 9 11 12 13 15 6 5 3 16 2 10 14
1 4 6 7 8 9 11 12 13 15 5 3 16 2 10 14
1 4 5 6 7 8 9 11 12 13 15 3 16 2 10 14
1 3 4 5 6 7 8 9 11 12 13 15 16 2 10 14
1 3 4 5 6 7 8 9 11 12 13 15 16 2 10 14
1 2 3 4 5 6 7 8 9 11 12 13 15 16 10 14
1 2 3 4 5 6 7 8 9 10 11 12 13 15 16 14
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16



Code using linked list:

#include <iostream>

using namespace std;

struct List
{
	int data;
	struct List *next;
} ;

void printList(struct List *head)
{
	struct List* ptr = head;
	while(ptr) {
		cout << ptr->data << " " ;
		ptr = ptr->next;
	}
	cout << endl;
}

struct List* createList(int a[], int sz)
{
	struct List *head = new struct List;
	struct List *current = head;
	
	for(int i = 0; i < sz; i++) {
		current->data = a[i];
		if (i == sz - 1 ) {
			current->next = NULL;
			break;
		}
		current->next = new struct List;
		current = current->next;
	}

	return head;
}

// from http://analgorithmaday.blogspot.com/2011/01/insertion-sort-with-linked-listin-place.html

struct List* insertion(struct List *head)
  {
      if(head == 0) return head;
   
      // unsorted list - from the 2nd element
      struct List *unsorted = head->next;
      while(unsorted != 0)
      {
          // take key as an element in the unsorted list.
          struct List *prev = 0;
          struct List *iter = head;
          struct List *key = unsorted;
   
          // iterate within the sorted list and find the position
          while(iter != 0)
          {
              if(iter->data < key->data)
              {
                  prev = iter;
                  iter = iter->next;
              }
               else
                  break;
          }
          unsorted = unsorted->next;
          // if reached the end of sorted list 
          if(iter == key) 
              continue;
   
          // note down the position to replace in a sorted list
          struct List *replace = iter;
   
          //move iter to end of the sorted list 
          while(iter->next != key) iter=iter->next;

		  // link to the upsorted list
          iter->next = unsorted;
   
          // delete the key and replace it in sorted list
          if(prev == 0) {
              head = key;
          } else {
                prev->next = key;
          }
          key->next = replace;
		  printList(head);
       }
       return head;
  }

int main()
{
	int a[] = { 15, 9, 8, 1, 4, 11, 7, 12, 13, 6, 5, 3, 16, 2, 10, 14};
	int size = sizeof(a)/sizeof(int);

	struct List *head = createList(a, size);
	printList(head);
	head = insertion(head);
	printList(head);
	
	cout << endl;
	return 0;
}


In place sort from the already sorted two sub arrays

Q: An array contains two sub- sorted arrays. Give an in-place algorithm to sort two sub arrays.

The following code uses the insertion sorting algorithm devised in the previous section.

We have an input array a[] = 1 4 5 7 8 9 2 3 6 10 11 composed of two sorted sub-arrays. We want to sort the array in place. In the process, we need to use swap() function which does in-place swap.

#include <iostream>

using namespace std;

void swap(int &x;, int &y;)
{
	x = x ^ y;
	y = x ^ y;
	x = x ^ y;
}

void insertion(int a[], int sz)
{
	for(int i=1; i  < sz; i++) {
		int j = i;
		while(j > 0) {
			if(a[j-1] > a[j]) swap(a[j-1],a[j]);
			j--;
		}
	}
	for(int i = 1; i < sz; i++) cout << a[i] << " ";
}

int main()
{
	int a[] = { 1, 4, 5, 7, 8, 9, 2, 3, 6, 10, 11 };
	int size = sizeof(a)/sizeof(int);
	for (int i = 0; i < size; i++) cout << a[i] << " ";
	cout << "  ==> " << endl;
	insertion(a, size);
	cout << endl;
	return 0;
}

Output:

1 4 5 7 8 9 2 3 6 10 11   ==>
2 3 4 5 6 7 8 9 10 11








Ph.D. / Golden Gate Ave, San Francisco / Seoul National Univ / Carnegie Mellon / UC Berkeley / DevOps / Deep Learning / Visualization

YouTubeMy YouTube channel

Sponsor Open Source development activities and free contents for everyone.

Thank you.

- K Hong





LIST OF ALGORITHMS



Algorithms - Introduction

Bubble Sort

Bucket Sort

Counting Sort

Heap Sort

Insertion Sort

Merge Sort

Quick Sort

Radix Sort - LSD

Selection Sort

Shell Sort



Queue/Priority Queue - Using linked list & Heap

Stack Data Structure

Trie Data Structure

Binary Tree Data Structure - BST

Hash Map/Hash Table

Linked List Data Structure

Closest Pair of Points

Spatial Data Structure and Physics Engines



Recursive Algorithms

Dynamic Programming

Knapsack Problems - Discrete Optimization

(Batch) Gradient Descent in python and scikit



Uniform Sampling on the Surface of a Sphere.

Bayes' Rule

Monty Hall Paradox

Compression Algorithm - Huffman Codes

Shannon Entropy

Path Finding Algorithm - A*

Dijkstra's Shortest Path

Prim's spanning tree algorithm in Python

Bellman-Ford Shortest Path

Encryption/Cryptography Algorithms

minHash

tf-idf weight

Natural Language Processing (NLP): Sentiment Analysis I (IMDb & bag-of-words)

Natural Language Processing (NLP): Sentiment Analysis II (tokenization, stemming, and stop words)

Natural Language Processing (NLP): Sentiment Analysis III (training & cross validation)

Natural Language Processing (NLP): Sentiment Analysis IV (out-of-core)

Locality-Sensitive Hashing (LSH) using Cosine Distance (Cosine Similarity)



Sponsor Open Source development activities and free contents for everyone.

Thank you.

- K Hong







Machine Learning with scikit-learn



scikit-learn installation

scikit-learn : Features and feature extraction - iris dataset

scikit-learn : Machine Learning Quick Preview

scikit-learn : Data Preprocessing I - Missing / Categorical data

scikit-learn : Data Preprocessing II - Partitioning a dataset / Feature scaling / Feature Selection / Regularization

scikit-learn : Data Preprocessing III - Dimensionality reduction vis Sequential feature selection / Assessing feature importance via random forests

Data Compression via Dimensionality Reduction I - Principal component analysis (PCA)

scikit-learn : Data Compression via Dimensionality Reduction II - Linear Discriminant Analysis (LDA)

scikit-learn : Data Compression via Dimensionality Reduction III - Nonlinear mappings via kernel principal component (KPCA) analysis

scikit-learn : Logistic Regression, Overfitting & regularization

scikit-learn : Supervised Learning & Unsupervised Learning - e.g. Unsupervised PCA dimensionality reduction with iris dataset

scikit-learn : Unsupervised_Learning - KMeans clustering with iris dataset

scikit-learn : Linearly Separable Data - Linear Model & (Gaussian) radial basis function kernel (RBF kernel)

scikit-learn : Decision Tree Learning I - Entropy, Gini, and Information Gain

scikit-learn : Decision Tree Learning II - Constructing the Decision Tree

scikit-learn : Random Decision Forests Classification

scikit-learn : Support Vector Machines (SVM)

scikit-learn : Support Vector Machines (SVM) II

Flask with Embedded Machine Learning I : Serializing with pickle and DB setup

Flask with Embedded Machine Learning II : Basic Flask App

Flask with Embedded Machine Learning III : Embedding Classifier

Flask with Embedded Machine Learning IV : Deploy

Flask with Embedded Machine Learning V : Updating the classifier

scikit-learn : Sample of a spam comment filter using SVM - classifying a good one or a bad one




Machine learning algorithms and concepts

Batch gradient descent algorithm

Single Layer Neural Network - Perceptron model on the Iris dataset using Heaviside step activation function

Batch gradient descent versus stochastic gradient descent

Single Layer Neural Network - Adaptive Linear Neuron using linear (identity) activation function with batch gradient descent method

Single Layer Neural Network : Adaptive Linear Neuron using linear (identity) activation function with stochastic gradient descent (SGD)

Logistic Regression

VC (Vapnik-Chervonenkis) Dimension and Shatter

Bias-variance tradeoff

Maximum Likelihood Estimation (MLE)

Neural Networks with backpropagation for XOR using one hidden layer

minHash

tf-idf weight

Natural Language Processing (NLP): Sentiment Analysis I (IMDb & bag-of-words)

Natural Language Processing (NLP): Sentiment Analysis II (tokenization, stemming, and stop words)

Natural Language Processing (NLP): Sentiment Analysis III (training & cross validation)

Natural Language Processing (NLP): Sentiment Analysis IV (out-of-core)

Locality-Sensitive Hashing (LSH) using Cosine Distance (Cosine Similarity)




Artificial Neural Networks (ANN)

[Note] Sources are available at Github - Jupyter notebook files

1. Introduction

2. Forward Propagation

3. Gradient Descent

4. Backpropagation of Errors

5. Checking gradient

6. Training via BFGS

7. Overfitting & Regularization

8. Deep Learning I : Image Recognition (Image uploading)

9. Deep Learning II : Image Recognition (Image classification)

10 - Deep Learning III : Deep Learning III : Theano, TensorFlow, and Keras




C++ Tutorials

C++ Home

Algorithms & Data Structures in C++ ...

Application (UI) - using Windows Forms (Visual Studio 2013/2012)

auto_ptr

Binary Tree Example Code

Blackjack with Qt

Boost - shared_ptr, weak_ptr, mpl, lambda, etc.

Boost.Asio (Socket Programming - Asynchronous TCP/IP)...

Classes and Structs

Constructor

C++11(C++0x): rvalue references, move constructor, and lambda, etc.

C++ API Testing

C++ Keywords - const, volatile, etc.

Debugging Crash & Memory Leak

Design Patterns in C++ ...

Dynamic Cast Operator

Eclipse CDT / JNI (Java Native Interface) / MinGW

Embedded Systems Programming I - Introduction

Embedded Systems Programming II - gcc ARM Toolchain and Simple Code on Ubuntu and Fedora

Embedded Systems Programming III - Eclipse CDT Plugin for gcc ARM Toolchain

Exceptions

Friend Functions and Friend Classes

fstream: input & output

Function Overloading

Functors (Function Objects) I - Introduction

Functors (Function Objects) II - Converting function to functor

Functors (Function Objects) - General



Git and GitHub Express...

GTest (Google Unit Test) with Visual Studio 2012

Inheritance & Virtual Inheritance (multiple inheritance)

Libraries - Static, Shared (Dynamic)

Linked List Basics

Linked List Examples

make & CMake

make (gnu)

Memory Allocation

Multi-Threaded Programming - Terminology - Semaphore, Mutex, Priority Inversion etc.

Multi-Threaded Programming II - Native Thread for Win32 (A)

Multi-Threaded Programming II - Native Thread for Win32 (B)

Multi-Threaded Programming II - Native Thread for Win32 (C)

Multi-Threaded Programming II - C++ Thread for Win32

Multi-Threaded Programming III - C/C++ Class Thread for Pthreads

MultiThreading/Parallel Programming - IPC

Multi-Threaded Programming with C++11 Part A (start, join(), detach(), and ownership)

Multi-Threaded Programming with C++11 Part B (Sharing Data - mutex, and race conditions, and deadlock)

Multithread Debugging

Object Returning

Object Slicing and Virtual Table

OpenCV with C++

Operator Overloading I

Operator Overloading II - self assignment

Pass by Value vs. Pass by Reference

Pointers

Pointers II - void pointers & arrays

Pointers III - pointer to function & multi-dimensional arrays

Preprocessor - Macro

Private Inheritance

Python & C++ with SIP

(Pseudo)-random numbers in C++

References for Built-in Types

Socket - Server & Client

Socket - Server & Client 2

Socket - Server & Client 3

Socket - Server & Client with Qt (Asynchronous / Multithreading / ThreadPool etc.)

Stack Unwinding

Standard Template Library (STL) I - Vector & List

Standard Template Library (STL) II - Maps

Standard Template Library (STL) II - unordered_map

Standard Template Library (STL) II - Sets

Standard Template Library (STL) III - Iterators

Standard Template Library (STL) IV - Algorithms

Standard Template Library (STL) V - Function Objects

Static Variables and Static Class Members

String

String II - sstream etc.

Taste of Assembly

Templates

Template Specialization

Template Specialization - Traits

Template Implementation & Compiler (.h or .cpp?)

The this Pointer

Type Cast Operators

Upcasting and Downcasting

Virtual Destructor & boost::shared_ptr

Virtual Functions



Programming Questions and Solutions ↓

Strings and Arrays

Linked List

Recursion

Bit Manipulation

Small Programs (string, memory functions etc.)

Math & Probability

Multithreading

140 Questions by Google



Qt 5 EXPRESS...

Win32 DLL ...

Articles On C++

What's new in C++11...

C++11 Threads EXPRESS...

Go Tutorial

OpenCV...


List of Design Patterns



Introduction

Abstract Factory Pattern

Adapter Pattern

Bridge Pattern

Chain of Responsibility

Command Pattern

Composite Pattern

Decorator Pattern

Delegation

Dependency Injection(DI) and Inversion of Control(IoC)

Façade Pattern

Factory Method

Model View Controller (MVC) Pattern

Observer Pattern

Prototype Pattern

Proxy Pattern

Singleton Pattern

Strategy Pattern

Template Method Pattern








Contact

BogoToBogo
contactus@bogotobogo.com

Follow Bogotobogo

About Us

contactus@bogotobogo.com

YouTubeMy YouTube channel
Pacific Ave, San Francisco, CA 94115

Pacific Ave, San Francisco, CA 94115

Copyright © 2024, bogotobogo
Design: Web Master