Java Code Implementation Of Selection Sort
Kushal Paudyal January 12th, 2010
Selection sort is a sorting algorithm, specifically an in-place comparison sort. It has O(n^2) 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.
The algorithm works as follows:
1. Find the minimum value in the list
2. Swap it with the value in the first position
3. Repeat the steps above for the remainder of the list (starting at the second position and advancing each time)
Effectively, we divide the list into two parts: the sublist of items already sorted, which we build up from left to right and is found at the beginning, and the sublist of items remaining to be sorted, occupying the remainder of the array.
Selection sort can also be used on list structures that make add and remove efficient, such as a linked list. In this case it’s more common to remove the minimum element from the remainder of the list, and then insert it at the end of the values sorted so far.
Variants of Selection Sort:
Heapsort greatly improves the basic algorithm by using an implicit heap data structure to speed up finding and removing the lowest datum. If implemented correctly, the heap will allow finding the next lowest element in T(log n) time instead of T(n) for the inner loop in normal selection sort, reducing the total running time to T(n log n).
A bidirectional variant of selection sort, called cocktail sort, is an algorithm which finds both the minimum and maximum values in the list in every pass. This reduces the number of scans of the list by a factor of 2, eliminating some loop overhead but not actually decreasing the number of comparisons or swaps. Note, however, that cocktail sort more often refers to a bidirectional variant of bubble sort.
Selection sort can be implemented as a stable sort. If, rather than swapping in step 2, the minimum value is inserted into the first position (that is, all intervening items moved down), the algorithm is stable. However, this modification either requires a data structure that supports efficient insertions or deletions, such as a linked list, or it leads to performing T(n^2) writes. Either way, it eliminates the main advantage of insertion sort (which is always stable) over selection sort.
In the bingo sort variant, items are ordered by repeatedly looking through the remaining items to find the greatest value and moving all items with that value to their final location. Like counting sort, this is an efficient variant if there are many duplicate values. Indeed, selection sort does one pass through the remaining items for each item moved. Bingo sort does two passes for each value (not item): one pass to find the next biggest value, and one pass to move every item with that value to its final location. Thus if on average there are more than two items with each value, bingo sort may be faster.
(Source Of The Above Text: Wikipedia
Text is available under the Creative Commons Attribution/Share-Alike License)
———————————-
The following is my implementation of Selection Sort in Java.
package com.kushal.sort;
/**
* SelectionSort.java
* @author Kushal Paudyal
* www.sanjaal.com/java
* Last Modified On: 2009-06-22
*/
public class SelectionSort {
/**
* This method takes an unsorted array of integers
* It then sorts the array and returns the sorted array.
* Uses Selection Sort algorithm for sorting.
*/
public static int[] selectionSort(int[] unsortedArray) {
int out, in, min;
for (out = 0; out < unsortedArray.length - 1; out++)
{
min = out;
for (in = out + 1; in < unsortedArray.length; in++)
if (unsortedArray[in] < unsortedArray[min])
min = in;
swap(unsortedArray, out, min);
}
return unsortedArray;
}
/**
* Swapping The Elements at two different indexes of an Arary
*/
private static void swap(int[] anArray, int firstIndex, int secondIndex) {
int temp = anArray[firstIndex];
anArray[firstIndex] = anArray[secondIndex];
anArray[secondIndex] = temp;
}
/**
* Method used for printing the contents of any array
*/
public static void printArray(int[] anyArray) {
for (int j = 0; j < anyArray.length; j++)
System.out.print(anyArray[j] + " ");
System.out.println("");
}
/**
* Testing the Selection Sort
*/
public static void main(String[] args) {
int[] unsortedArray = { 98, 45, 63, 22, 23, 12, 87, 34, 45, 43, 90, 12 };
System.out.print("Unsorted Array :");
printArray(unsortedArray);
int[] sortedArray = selectionSort(unsortedArray);
System.out.print("Sorted Array :");
printArray(sortedArray);
}
/*
* SANJAAL CORPS MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF
* THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
* TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE, OR NON-INFRINGEMENT. SANJAAL CORPS SHALL NOT BE LIABLE FOR
* ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
* DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
*
* THIS SOFTWARE IS NOT DESIGNED OR INTENDED FOR USE OR RESALE AS ON-LINE
* CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING FAIL-SAFE
* PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, AIRCRAFT
* NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT LIFE
* SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE
* SOFTWARE COULD LEAD DIRECTLY TO DEATH, PERSONAL INJURY, OR SEVERE
* PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH RISK ACTIVITIES"). SANJAAL CORPS
* SPECIFICALLY DISCLAIMS ANY EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR
* HIGH RISK ACTIVITIES.
*/
}
====================================
Here is the sample output of this program:
Unsorted Array :98 45 63 22 23 12 87 34 45 43 90 12 Sorted Array :12 12 22 23 34 43 45 45 63 87 90 98
Sanjaal.com is owned and maintained by Sanjaal Corps, Nepal. The company offers Webhosting and Domain Registration Services, IT Solutions and Business Analysis. Sanjaal.com website features H1B Visa Information, Entertainment Portal, Link Directory Service, Free Articles, Free Open Source Tutorials on Java and J2EE Platform, Digital Photography, High Resolution Picture Gallery and Free Reliable Image Hosting Services. Future plan includes Open Source Software Development Portal, Technical Solutions and Customizable Movie and Music Arena. We would be introducing data backup, data recovery, data hosting and voip solutions. Stay free from phishing – our website does not ask for your credit card and banking information. Happy Surfing!
Originally posted 2009-06-25 12:19:07.
