Skip to main content

Selection Sort Algorithm in Java and Python

The next definition is from Wikipedia:

"In computer science, a Selection sort is a sorting algorithm, specifically an in-place comparison sort. It has O(n2) time complexity, making it inefficient on large lists, and generally performs worse than the similar insertion sort. Selection sort is noted for its simplicity, and also has performance advantages over more complicated algorithms in certain situations, particularly where auxiliary memory is limited."

It mentions also they are variants of this algorithm: heapsort, cocktail sort, bingo sort.

Also there is a table where n is the number of records to be sorted. The columns "Average" and "Worst" give the time complexity in each case.

Name Best Average Worst
Selection sort  \mathcal{} n^2  \mathcal{} n^2  \mathcal{} n^2

Now, here the code in Java (take in account that I will implement the same interface and use the same tool class and it was defined in Insertion Sort Algorithm).



package melg.algorithms.sorting;

/**
 * @author Manuel Loayza
 * 
 */
public class SelectionSortAlgorithm implements ISorting {

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

 /**
  * Implementation of Selection 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();
  int initPosition = 0, minPosition = 0;
  for (initPosition = 0; initPosition < (array.length - 1); initPosition++) {
   minPosition = initPosition;
   if (debug) {
    System.out.format("Reviewing the %d element (%d)\n",
      initPosition + 1, array[initPosition]);
   }
   for (int j = initPosition + 1; j < array.length; j++) {
    if (array[j] < array[minPosition]) {
     minPosition = j;
    }
    numberOfIteration++;
   }
   if (minPosition != initPosition) {
    // swapping the values
    long temp = array[minPosition];
    array[minPosition] = array[initPosition];
    array[initPosition] = temp;
    if (debug) {
     System.out.format("There is a min value: (%d)\n",
       array[initPosition]);
     SortUtilAlgorithm.showArray(array);
    }
   }
   numberOfIteration++;
  }
  runningTime = System.nanoTime() - runningTime;
  return array;
 }

 @Override
 public String getStats() {
  return SortUtilAlgorithm.getStats(runningTime, numberOfIteration);
 }

 public static void main(String... args) {
  long array[] = SortUtilAlgorithm.genereteArray(20, 100);
  System.out.println("Source array has a size of : " + array.length);
  SortUtilAlgorithm.showArray(array);
  ISorting algorithm = new SelectionSortAlgorithm();
  array = algorithm.makeSorting(array, false);
  SortUtilAlgorithm.showArray(array);
  System.out.println(algorithm.getStats());
 }
}
For the code in Python, I have using an abstract and a little variation of the Template Pattern. Python do not use interface because it allows multiple inheritance, so it does not need the use of interfaces like Java.
The template class is named SortingBase, as it is defined as following:
'''
Created on 21/03/2012

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

import math
from random import random 
from decimal import Decimal

class SortingBase(object):
    '''
    classdocs
    '''

    def __init__(self):
        '''
        Constructor
        '''
        self.numberOfIterations = 0
        self.runningTime = Decimal('0')
        
    '''
    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)

    '''
    Show statistics information
    '''
    def getStats(self):
        stats = 'Time of Execution:\t {0:.30f} s.\n'.format(self.runningTime)
        stats += 'Number of Iterations:\t {0}.\n'.format(self.numberOfIterations)
        return stats

    def generateArray(self, factorSize, factorMaxValue):
        array = []
        items = int(math.floor(random() * factorSize))
        for i in range (0, items):
            array.append(int(math.floor(random() * factorMaxValue)))    
        return array
 
    def makeSorting(self, array, debug):
        raise NotImplementedError( "Should have implemented this" )
    

The selection sort class python is:


'''
Created on 21/03/2012

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

'''
import time
from decimal import getcontext, Decimal
from melg.algorithms.sorting.algorithmbase import SortingBase

class SelectionSortAlgorithm(SortingBase):
    def __init__(self):
        SortingBase.__init__(self)
        getcontext().prec = 22
        self.start = None
        self.end = None
        
    '''
    Implementation of the Selection Sort Algorithm
    '''
    def makeSorting(self, array, debug):
        self.start = Decimal(time.time())
        #print self.start
        size = len(array)
        initPosition = 0
        minPosition = 0
        for initPosition in range(size - 1):
            minPosition = initPosition
            if debug:
                print("Reviewing the {0} element {1}".format(initPosition + 1, array[initPosition]))
            for j in range(initPosition + 1, size):
                if array[j] < array[minPosition]:
                    minPosition = j
                self.numberOfIterations += 1
            if minPosition != initPosition:
                temp = array[minPosition]
                array[minPosition] = array[initPosition]
                array[initPosition] = temp
                if debug:
                    print("There is a min value: {0}".format(temp))
                    self.showArray(array)
            self.numberOfIterations += 1
            
        self.end = Decimal(time.time())
        #print self.end
        self.runningTime = self.end - self.start
        return array

if __name__ == "__main__":
    sorting = SelectionSortAlgorithm()
    myarray = sorting.generateArray(20, 100)
    print("The source array has a size of : {0}".format(len(myarray))) 
    sorting.showArray(myarray)
    myarray = sorting.makeSorting(myarray, False)
    print("The sorted target array")
    sorting.showArray(myarray)
    print sorting.getStats()


I'd want finished by making a little comparison between performance between these 2 languages. For arrays with size around less than 100, the time of sorting in Python is almost zero, and in Java is near to 0.001 seconds. But when the array size is bigger, maybe greater than 1500 elements, in Java, time of sorting the array take almost the same time for the previous 100 element, instead Python took around 0.3 seconds. I have done a lot of attempts, and Java always had a better performance than Python for big arrays.

In my next post I will talk about merge sort algorithm.

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

WebDynpro for Java: Tutorial of the Basic Usage of RoadMap Component

We will create a local Development component project of the type Web Dynpro as follow Our project will contain only 3 views with the purpose of show the basic usage of the roadMap object. After, we create our component controller RoadMap and the RoadMapView view as follow Now, we will create the 2 views more, the previous one will contain only the RoadMap Object (RoadMapView) used in all the project, the other ones show the flow between screens. Here the list of the 3 views: RoadMapView,  InitView, and ConfirmView. Now, we will add the component RoadMap object (it is on the Standar Complex Group) to the RoadMapView view, but first delete the default object added to the view, after we will need to add two steps (it could be more, depends of your logic) to our roadmap object. In order to do that we will use the Outline view of the NWDS. We add the two steps as follow The type steps to add at the RoadMap object will be ot the "RoadMapStep" type. The name of the steps are: Init