Skip to main content

Insertion Sort Algorithm in Java and Python

I've started to study more about algorithms. I think that it will be an excellent challenge and great experience.
I found this course in MIT Open CourseWare website :  "Introduction to Algorithms (SMA 5503)", and I'm studying from this resource and also I've bought the related book to this course.

Well, I'm going to post entries related to algorithms in Java, Groovy and Python language (my new lovers :) ).
For Java coding I'm going to create an interface to be implemented for all my algorithm classes.


package melg.algorithms.sorting;

public interface ISorting {

 long[] makeSorting(long[] array, boolean debug);
 
 String getStats();
}
Also I'll use this tool class, in order to be used for debugging purpose:

package melg.algorithms.sorting;


public class SortUtilAlgorithm {

 /**
  * Prints in the console the items of the array object
  * 
  * @param array
  *            the array object.
  */
 public static void showArray(long[] array) {
  System.out.print("[");
  for (int i = 0; i < array.length; i++) {
   System.out.print(array[i]);
   if (i != (array.length - 1)) {
    System.out.print(",");
   } else {
    System.out.println("]");
   }
  }
 }

 /**
  * Generates an array object with long numbers.
  * 
  * @param factorItems
  *            factor for number of items of the array
  * @param factorMaxValue
  *            factor for the maximum value of long numbers
  * @return
  */
 public static long[] genereteArray(int factorItems, long factorMaxValue) {
  Double items = Math.ceil(Math.random() * factorItems);
  long[] array = new long[items.intValue()];
  for (int i = 0; i < items.intValue(); i++) {
   array[i] = (long) Math.ceil(Math.random() * factorMaxValue);
  }
  return array;
 }

 /**
  * Returns a string containing statistics information.
  * 
  * @param rt   running time
  * @param noi   number of iterations
  * @return
  */
 public static String getStats(long rt, long noi) {
  StringBuilder str = new StringBuilder();
  double seconds = rt / (Math.pow(10, 9));
  String strSeconds = String.format("%10.10f", seconds);
  str.append("Time of Execution:\t").append(rt).append(" ns.\n")
    .append("\t\t\t").append(String.valueOf(strSeconds))
    .append(" s.\n").append("Number of Total Iterations:\t")
    .append(noi).append(" times.\n");
  return str.toString();
 }
}


Next, I show the implementation class of the Insertion Sort algorithm.
package melg.algorithms.sorting;

public class InsertionSortAlgorithm implements ISorting {

 private long runningTime = 0;
 private long numberOfIteration = 0;

 /**
  * Implementation of Insertion sort Algorithm
  * 
  * @param array
  *            array object of long values to be sorted.
  * @return the sorted array
  */
 public long[] makeSorting(long[] array, boolean debug) {
  runningTime = System.nanoTime();
  for (int i = 1; i < array.length; i++) {
   long key = array[i];
   int j = i - 1;
   if (debug)
    System.out.println("Inserting:" + key);
   while (j >= 0 && array[j] > key) {
    array[j + 1] = array[j];
    // A[j] = key;
    j--;
    if (debug)
     SortUtilAlgorithm.showArray(array);
    numberOfIteration++;
   }
   array[j + 1] = key;
   if (debug) {
    System.out.println("Inserted:" + key);
    SortUtilAlgorithm.showArray(array);
   }
   numberOfIteration++;
  }
  runningTime = System.nanoTime() - runningTime;
  return array;
 }

 public static void main(String... args) {
  long array[] = SortUtilAlgorithm.genereteArray(10, 200);
  System.out.println("Source array has a size of : " + array.length);
  SortUtilAlgorithm.showArray(array);
  ISorting algorithm = new InsertionSortAlgorithm();
  array = algorithm.makeSorting(array, true);
  SortUtilAlgorithm.showArray(array);
  System.out.println(algorithm.getStats());
 }

 @Override
 public String getStats() {
  return SortUtilAlgorithm.getStats(runningTime, numberOfIteration);
 }
}
Here one output of the running class:
Source array has a size of : 8
[74,142,54,89,76,176,147,92]
Inserting:142
Inserted:142
[74,142,54,89,76,176,147,92]
Inserting:54
[74,142,142,89,76,176,147,92]
[74,74,142,89,76,176,147,92]
Inserted:54
[54,74,142,89,76,176,147,92]
Inserting:89
[54,74,142,142,76,176,147,92]
Inserted:89
[54,74,89,142,76,176,147,92]
Inserting:76
[54,74,89,142,142,176,147,92]
[54,74,89,89,142,176,147,92]
Inserted:76
[54,74,76,89,142,176,147,92]
Inserting:176
Inserted:176
[54,74,76,89,142,176,147,92]
Inserting:147
[54,74,76,89,142,176,176,92]
Inserted:147
[54,74,76,89,142,147,176,92]
Inserting:92
[54,74,76,89,142,147,176,176]
[54,74,76,89,142,147,147,176]
[54,74,76,89,142,142,147,176]
Inserted:92
[54,74,76,89,92,142,147,176]
[54,74,76,89,92,142,147,176]
Time of Execution: 5054274 ns.
   0.0050542740 s.
Number of Total Iterations: 16 times.
Also I like to add the code of this sorting algorithms in Python. Why? Because I love it :). I have started to learn others languages than Java Python and Groovy, and maybe a little Ruby. Next the code for Python language, it was tested with Python 2.7, for python 3.0 there is a issue with conversion from float to integer. In Python 3, they are explicit, and in Python 2.7, you need to do the casting to integer with int() operation.
'''
Created on 15/03/2012

@author: Manuel Loayza
@contact: mloayzagahona at gmail dot com
'''

import math
from random import random 

class InsertionSortAlgorithm:
    def __init__(self):
        pass
            
    '''
    Implementation of the Insertion Sort Algorithm
    '''
    def makeSorting(self, array, debug):
        size = len(array)
        for i in range(1, size):
            key = array[i]
            j = i - 1
            if debug: 
                print("Verifying element: {0}".format(key))
            while (j >= 0 and key < array[j]) :
                array[j + 1] = array[j]
                j -= 1
                if debug :
                    self.showArray(myarray)
            array[j + 1] = key
            if debug: 
                print("Element Inserted: {0}".format(key))
                self.showArray(myarray)
    
    '''
    Shows the array in the console
    '''
    def showArray(self, array):
        size = len(array)
        string = "["
        for i in range(0, size):
            string = string + "%s" % array[i]
            if i != (size - 1) :
                string = string + ","
            else:
                string = string + "]"
        print(string)
        
if __name__ == "__main__":
    sorting = InsertionSortAlgorithm()
    myarray = []
    items = int(math.floor(random() * 20))
    for i in range (0, items):
        myarray.append(int(math.floor(random() * 200)))    
    print("The source array has a size of : {0}".format(items)) 
    sorting.showArray(myarray)
    sorting.makeSorting(myarray, True)
    print("The target sorted array")
    sorting.showArray(myarray)
Here one execution of this python code.
The source array has a size of : 5
[13,33,27,13,4]
Verifying element: 33
Element Inserted: 33
[13,33,27,13,4]
Verifying element: 27
[13,33,33,13,4]
Element Inserted: 27
[13,27,33,13,4]
Verifying element: 13
[13,27,33,33,4]
[13,27,27,33,4]
Element Inserted: 13
[13,13,27,33,4]
Verifying element: 4
[13,13,27,33,33]
[13,13,27,27,33]
[13,13,13,27,33]
[13,13,13,27,33]
Element Inserted: 4
[4,13,13,27,33]
The target sorted array
[4,13,13,27,33]
Finally, the code of this algorithm in Groovy.
package melg.algorithms.sorting


class InsertionSortAlgorithm {

 private boolean debug = false
 /*
  * Implementation of the Insertion Sort Algorithm
  */
 public void makeSorting(array){
  int items = array.size()
  for (i in 1..< items){
   long key = (long)array[i]
   int j = i - 1
   if (debug) println "The value ${key} is being verified."
   while (j >= 0 && key < array[j]) {
    array[j+1] = array[j]
    j = j - 1
    if (debug)showArray(array)
   }
   array[j+1] = key
   if (debug) {
    println "The value ${key} was inserted."
    showArray(array)
   }
  }
 }

 def void setDebug(value){
  this.debug = value
 }

 public static void showArray(array){
  print "["
  int size = array.size(), count = 0;
  array.each{
   print it
   if (size > (count + 1)){
    print ","
   }
   count++
  }
  println "]"
 }
}

def array = []
float size = Math.ceil(Math.random() * 3500 )
for (i in 0..< size.toInteger()){
 array << Math.ceil(Math.random() * 65000 ).toInteger()
}

InsertionSortAlgorithm insertion = new InsertionSortAlgorithm();
println "The source array has ${array.size()} items."
InsertionSortAlgorithm.showArray(array);
insertion.makeSorting(array);
println "\nThe target sorted array is:."
InsertionSortAlgorithm.showArray(array);
It is the result of my first try with sorting algorithms, maybe later I'm going to add some theory and maths about this kind of algorithm.

Good luck.

Comments

Popular posts from this blog

My first serious Groovy class ..... decompiling java classes with closures

After I read the chapter 6 "closures" of the book Groovy and Grails Recipe, and I decided to use the power of closures of Groovy for resource (files) with other problem that I had, decompile in one step every class of jar library. Well, the purpose of this class is call an external java decompiler (jad) from a Groovy class and execute the command into directory where the jar file was decompressed. And by using the power of closures executes recursively into this directory until find the classes. Well, no more words, here the class package demo class Executor { // directory where the library(jar) was decompressed def path /** * Execute the decompilation of the classes into the directory defined in the path * @return */ def decompileClasses(){ def directory = new File(path) //make use of closures defined in the Object class directory.eachFileRecurse { def name = it.absolutePath //if the current resource hasn't a .class extension continues with...

How to .. Integration Non-SAP J2EE-based Web Applications into SAP Portal with SSO Part 1

We are going to integrate Non-SAP J2EE-based Web Applications into the SAP Portal with Application Integrator and SSO. In this part, I will discuss the overall of these posts and configure the iView with Application Integrator Overview of Integration. To perform this integration must take into account the following steps: Deployment of the portal application for the creation of the system portal object Create and set the type of Application Integrator iView that will contain the applications to integrate. Installing SAPSSOEXT and SAPSECU libraries Deployment of the application gateway called SsoGatewayWeb Changing the target application. This integration has the following restrictions: It applies only for web applications based on J2EE Servlet. Depend exclusively on the sucessful load of the libraries supported by SAP (sapssoext and sapsecu) in both Windows and UNIX environments. The target application must have created a profile for the user id logged to the SAP portal, this sh...

How to .. Integration Non-SAP J2EE-based Web Applications into SAP Portal with SSO Part 2

After we have configured our portal object, we must install the gateway application and modified the target application. 1. Deployment of the Gateway Web J2EE Application : We must to create an j2ee web application with the purpose to be a gateway from every application that want to validate the SAP Ticket Logon. I have created this application because of the problem with the sapssoext library provied from SAP, it can't be loaded from more than one classloader, then this new web application will be the unque application on the server that can load this library. This application could expose 2 or more services, it depends of you. I will mention 2 services: /SsoGatewayWeb/ssojson.dtx : under this URI will happen the vaidation of the SAP Ticket Logon sent by the SAP Portal, it returns a JSON string with the information retrieved from the ticket. /SsoGatewayWeb/sendsso2cookietest : this URI generates HTML content, it generates the string ACL of the certificate file. Both only acc...