Java Code Implementation Of Selection Sort

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

Originally posted 2009-06-25 12:19:07.

Share

Tutorial on Converting an List of Strings or Numbers to a CSV file with optional sorting

Chances are you might have needed to convert a list of strings or numbers to a CSV file while you were programming something. An example is that in any java program you might have obtained a list of states of United States stored in your ArrayList object and then you wanted to have them in a CSV format so that you probably could load it to a database or use it for some other purposes.

I wrote this tool to serve the same purpose.

Here are the basic features this simple java example can do. Given a list of String objects stored in an ArrayList, this program can:

  • Convert Strings or numbers stored in an ArrayList object to comma separated strings
  • Print the comma separated values (CSV) to either console or file
  • Optionally you can sort the the list before you do the conversion.
package com.kushal.tools;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

/**
 * @author Kushal Paudyal 
 * Last Modified on 2011-09-06 This utility converts a
 * list to comma separated values. Intended to be used with Strings and
 * can be modified with numbers.
 * 
 * Have options to write the converted values to either console or file.
 */
public class ListToCSV {
	private static boolean writeCSVToConsole = true;
	private static boolean writeCSVToFile = true;
	private static String destinationCSVFile = "C:\\temp\\convertedCSV.csv";
	private static boolean sortTheList = true;

	public static void main(String[] args) {
		ListToCSV util = new ListToCSV();
		List<String> sampleList = util.createSampleList();
		util.convertAndPrint(sampleList, writeCSVToConsole, writeCSVToFile, sortTheList);

	}

	/**
	 * @param sampleList - input list of string
	 * @param writeToConsole - if this flag is true, writes to console
	 * @param writeToFile - if this flag is true writes to file.
	 * @param sortTheList - if the list is to be sorted before conversion
	 */
	private void convertAndPrint(List<String> sampleList,
			boolean writeToConsole, boolean writeToFile, boolean sortTheList) {
		String commaSeparatedValues = "";

		/** If the list is not null and the list size is not zero, do the processing**/
		if (sampleList != null) {
			/** Sort the list if sortTheList was passed as true**/
			if(sortTheList) {
				Collections.sort(sampleList);
			}
			/**Iterate through the list and append comma after each values**/
			Iterator<String> iter = sampleList.iterator();
			while (iter.hasNext()) {
				commaSeparatedValues += iter.next() + ",";
			}
			/**Remove the last comma**/
			if (commaSeparatedValues.endsWith(",")) {
				commaSeparatedValues = commaSeparatedValues.substring(0,
						commaSeparatedValues.lastIndexOf(","));
			}
		}
		/** If writeToConsole flag was passed as true, output to console**/
		if(writeToConsole) {
			System.out.println(commaSeparatedValues);
		}
		/** If writeToFile flag was passed as true, output to File**/		
		if(writeToFile) {
			try {
				FileWriter fstream = new FileWriter(destinationCSVFile, false);
				BufferedWriter out = new BufferedWriter(fstream);
				out.write(commaSeparatedValues);
				out.close();
				System.out.println("*** Also wrote this information to file: " + destinationCSVFile);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}

	/**
	 * Creates a sample list to be used by the convertAndPrint method
	 * and returns it to the calling method. 
	 */
	private List<String> createSampleList() {
		List<String> sampleList = new ArrayList<String>();
		sampleList.add("Nebraska");
		sampleList.add("Iowa");
		sampleList.add("Illinois");
		sampleList.add("Idaho");
		return sampleList;
	}
}
Blog Widget by LinkWithin

Originally posted 2011-09-16 18:54:06.

Share