Strand sort

Strand Sort Animation

Strand sort is a recursive sorting algorithm that sorts items of a list into increasing order. It has O(n2) worst-case time complexity, which occurs when the input list is reverse sorted.[1] It has a best-case time complexity of O(n), which occurs when the input is already sorted.[citation needed]

The algorithm first moves the first element of a list into a sub-list.[1] It then compares the last element in the sub-list to each subsequent element in the original list.[1] Once there is an element in the original list that is greater than the last element in the sub-list, the element is removed from the original list and added to the sub-list.[1] This process continues until the last element in the sub-list is compared to the remaining elements in the original list.[1] The sub-list is then merged into a new list.[1] Repeat this process and merge all sub-lists until all elements are sorted.[1] This algorithm is called strand sort because there are strands of sorted elements within the unsorted elements that are removed one at a time.[1] This algorithm is also used in J Sort for fewer than 40 elements.[2]

Example

This example is based on the description of the algorithm provided in the book IT Enabled Practices and Emerging Management Paradigms.[1]

Step 1: Start with a list of numbers: {5, 1, 4, 2, 0, 9, 6, 3, 8, 7}.

Step 2: Next, move the first element of the list into a new sub-list: sub-list contains {5}.

Step 3: Then, iterate through the original list and compare each number to 5 until there is a number greater than 5.

  • 1 < 5, so 1 is not added to the sub-list.
  • 4 < 5, so 4 is not added to the sub-list.
  • 2 < 5, so 2 is not added to the sub-list.
  • 0 < 5, so 0  is not added to the sub-list.
  • 9 > 5, so 9 is added to the sub-list and removed from the original list.

Step 4: Now compare 9 with the remaining elements in the original list until there is a number greater than 9.  

  • 6 < 9, so 6 is not added to the sub-list.
  • 3 < 9, so 3 is not added to the sub-list.
  • 8 < 9, so 8 is not added to the sub-list.
  • 7 < 9, so 7 is not added to the sub-list.

Step 5: Now there are no more elements to compare 9 to, so merge the sub-list into a new list, called solution-list.

After step 5, the original list contains {1, 4, 2, 0, 6, 3, 8, 7}.

The sub-list is empty, and the solution list contains {5, 9}.

Step 6: Move the first element of the original list into sub-list: sub-list contains {1}.

Step 7: Iterate through the original list and compare each number to 1 until there is a number greater than 1.

  • 4 > 1, so 4 is added to the sub-list and 4 is removed from the original list.

Step 8: Now compare 4 with the remaining elements in the original list until there is a number greater than 4.

  • 2 < 4, so 2 is not added to the sub-list.
  • 0 < 4, so 0 is not added to the sub-list.
  • 6 > 4, so 6 is added to the sub-list and is removed from the original list.

Step 9: Now compare 6 with the remaining elements in the original list until there is a number greater than 6.  

  • 3 < 6, so 3 is not added to the sub-list.
  • 8 > 6, so 8 is added to the sub-list and is removed from the original list.

Step 10: Now compare 8 with the remaining elements in the original list until there is a number greater than 8.

  • 7 < 8, so 7 is not added to the sub-list.

Step 11: Since there are no more elements in the original list to compare {8} to, the sub-list is merged with the solution list. Now the original list contains {2, 0, 3, 7}, the sub-list is empty, and the solution-list contains {1, 4, 5, 6, 8, 9}.

Step 12:  Move the first element of the original list into sub-list. Sub-list contains {2}.

Step 13: Iterate through the original list and compare each number to 2 until there is a number greater than 2.

  • 0 < 2, so 0 is not added to the sub-list.
  • 3 > 2, so 3 is added to the sub-list and is removed from the original list.

Step 14: Now compare 3 with the remaining elements in the original list until there is a number greater than 3.

  • 7 > 3, so 7 is added to the sub-list and is removed from the original list.

Step 15: Since there are no more elements in the original list to compare {7} to, the sub-list is merged with the solution list. The original list now contains {0}, the sub-list is empty, and solution list contains {1, 2, 3, 4, 5, 6, 7, 8, 9}.

Step 16:  Move the first element of the original list into sub-list. Sub-list contains {0}.

Step 17:  Since the original list is now empty, the sub-list is merged with the solution list. The solution list now contains {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}. There are now no more elements in the original list, and all of the elements in the solution list have successfully been sorted into increasing numerical order.

Implementation

Since Strand Sort requires many insertions and deletions, it is best to use a linked list when implementing the algorithm.[3] Linked lists require constant time for both insertions and removals of elements using iterators. The time to traverse through the linked list is directly related to the input size of the list.[4] The following implementation is done in Java 8 and is based on the description of the algorithm from the book IT Enabled Practices and Emerging Management Paradigms.[1]

package strandSort;

import java.util.*;

public class strandSort {
	static LinkedList<Integer> solList = new LinkedList<Integer>();
	static int k = 0;

	/**
	 * This is a recursive Strand Sort method. It takes in a linked list of
	 * integers as its parameter. It first checks the base case to see if the
	 * linked list is empty. Then proceeds to the Strand sort algorithm until
	 * the linked list is empty.
	 * 
	 * @param origList:
	 *            a linked list of integers
	 */
	public static void strandSortIterative(LinkedList<Integer> origList) {

		// Base Case
		if (origList.isEmpty()) {
			return;
		}

		else {
			// Create the subList and add the first element of
			// The original linked list to the sublist.
			// Then remove the first element from the original list.
			LinkedList<Integer> subList = new LinkedList<Integer>();
			subList.add(origList.getFirst());
			origList.removeFirst();

			// Iterate through the original list, checking if any elements are
			// Greater than the element in the sub list.
			int index = 0;
			for (int j = 0; j < origList.size(); j++) {
				if (origList.get(j) > subList.get(index)) {
					subList.add(origList.get(j));
					origList.remove(j);
					j = j - 1;
					index = index + 1;
				}
			}
			// Merge sub-list into solution list.
			// There are two cases for this step/
			// Case 1: The first recursive call, add all of the elements to the
			// solution list in sequential order
			if (k == 0) {
				for (int i = 0; i < subList.size(); i++) {

					solList.add(subList.get(i));
					k = k + 1;
				}

			}

			// Case 2: After the first recursive call, 
			// merge the sub-list with the solution list.
			// This works by comparing the greatest element in the sublist (which is always the last element)
			// with the first element in the solution list. 
			else {
				int subEnd = subList.size() - 1;
				int solStart = 0;
				while (!subList.isEmpty()) {

					if (subList.get(subEnd) > solList.get(solStart)) {
						solStart++;

					} else {
						solList.add(solStart, subList.get(subEnd));
						subList.remove(subEnd);
						subEnd--;
						solStart = 0;
					}

				}

			}

			strandSortIterative(origList);
		}

	}

	public static void main(String[] args) {
		// Create a new linked list of Integers
		LinkedList<Integer> origList = new LinkedList<Integer>();

		// Add the following integers to the linked list: {5, 1, 4, 2, 0, 9, 6, 3, 8, 7}

		origList.add(5);
		origList.add(1);
		origList.add(4);
		origList.add(2);
		origList.add(0);
		origList.add(9);
		origList.add(6);
		origList.add(3);
		origList.add(8);
		origList.add(7);

		strandSortIterative(origList);
		// Print out the solution list
		for (int i = 0; i < solList.size(); i++) {
			System.out.println(solList.get(i));
		}

	}

}

References

  1. ^ a b c d e f g h i j IT enabled practices and emerging management paradigms. Gupta, I. C. (Ishwar Chandra), 1946-, Jaroliya, Deepak., Prestige Institute of Management and Research. (1st ed.). Indore: Prestige Institute of Management and Research. 2008. ISBN 9788174466761. OCLC 641462443.{{cite book}}: CS1 maint: others (link)
  2. ^ Sudipta., Mukherjee (2008). Data structures using C : 1000 problems and solutions. New Delhi: Tata McGraw-Hill. ISBN 9780070667655. OCLC 311311576.
  3. ^ "strand sort". xlinux.nist.gov. Retrieved 2018-11-06.
  4. ^ "LinkedLists". www.cs.cmu.edu. Retrieved 2018-11-06.

Read other articles:

In 2004 a new postal code system was introduced in Iraq. Iraqi Post has developed a comprehensive Postal Code numbering system that will ensure more efficient mail sorting and accuracy of delivery of your correspondence. The new postal system was rededicated in 2004. The system is numeric and utilizes five digits that correspond to the Region, governorate as well as the post office within that governorate. Mail Address Format: Examples: Recipients Name Company Name (if any) PO Box # or Street...

 

Plan for an Oxford–Cambridge railway line This article is about the proposed English railway line between Oxford and Cambridge. For the proposed railway in Nepal, see East-West Railway. For the proposed railway in Massachusetts, see East-West Passenger Rail (Massachusetts). For other uses, see East–West line. East West RailLocationOxfordshireBuckinghamshireBedfordshireCambridgeshireProposerEast West Main Line PartnershipProject websiteeastwestrail.co.ukStatusOxford–Bedford: Under constr...

 

French soldier Claude de Roux, chevalier de Saint-LaurentGovernor of Saint ChristopheIn officeApril 1666 – February 1689Preceded byCharles de SalesSucceeded byCharles de Pechpeyrou-Comminges de GuitautGovernor general of the French Antilles (acting)In officeMarch 1683 – June 1684Preceded byCharles de Courbon de BlénacSucceeded byCharles de Courbon de BlénacGovernor of Martinique (interim)In officeFebruary 1689 – 31 March 1689Preceded byCharles de Pechpeyrou-...

Specialized form of regression analysis, in statistics Part of a series onRegression analysis Models Linear regression Simple regression Polynomial regression General linear model Generalized linear model Vector generalized linear model Discrete choice Binomial regression Binary regression Logistic regression Multinomial logistic regression Mixed logit Probit Multinomial probit Ordered logit Ordered probit Poisson Multilevel model Fixed effects Random effects Linear mixed-effects model Nonlin...

 

American biotechnology corporation Genentech, Inc.Company typeSubsidiaryIndustryBiotechnologyFounded1976; 48 years ago (1976)HeadquartersSouth San Francisco, California, United StatesKey peopleAshley Magargee(interim CEO)[1]Ed HarringtonLevi GarrawayStephen WilliamsSean JohnstonSeverin Schwan(Chairman of Genentech Board of Directors, CEO of Roche Group)Anna BattAviv Regev[2][3]ProductsAvastin, Herceptin, Rituxan, Perjeta, Kadcyla, Gazyva, Tarceva, Ocr...

 

Eukaryotes other than animals, plants or fungi For the journal, see Protist (journal). ProtistsTemporal range: Paleoproterozoic – Present Pha. Proterozoic Archean Had. Examples of protists. Clockwise from top left: red algae, kelp, ciliate, golden alga, dinoflagellate, metamonad, amoeba, slime mold. Scientific classification(paraphyletic) Domain: Eukaryota Supergroups[1] Amorphea (including fungi & animals) Apusomonadida Archaeplastida (including land plants) Breviatea CRuMs Cry...

Physical constant: Electric charge of one mole of electrons Not to be confused with farad. Faraday constantMichael Faraday, the constant's namesakeCommon symbolsFSI unitcoulomb per mole (C/mol)In SI base unitss⋅A⋅mol−1Derivations fromother quantitiesF = eNAValue9.64853321233100184×104 C⋅mol−1 In physical chemistry, the Faraday constant (symbol F, sometimes stylized as ℱ) is a physical constant defined as the quotient of the total electric charge (q) by the amou...

 

UK record label; imprint of Universal Music Operations Ltd. This article needs additional citations for verification. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sources: Universal Music TV – news · newspapers · books · scholar · JSTOR (November 2008) (Learn how and when to remove this message) Universal Music TVParent companyUniversal Music GroupFounded1998GenreVarious...

 

 Bene protetto dall'UNESCOGrande île, nel centro di Strasburgo Patrimonio dell'umanità TipoCulturali Criterio(i) (ii) (iv) PericoloNon in pericolo Riconosciuto dal1988 Scheda UNESCO(EN) Strasbourg – Grande île(FR) Scheda Manuale Cattedrale di Notre-Dame Palazzo dei Rohan visto dal fiume Ill Piazza della Cattedrale e la Maison Kammerzell (a destra) La Grande Île (Grande isola), la più centrale e caratteristica isola di Strasburgo, costituisce il centro storico della città ed ...

Cet article est une ébauche concernant l’art et une chronologie ou une date. Vous pouvez partager vos connaissances en l’améliorant (comment ?) selon les recommandations des projets correspondants. Chronologies Données clés 1710 1711 1712  1713  1714 1715 1716Décennies :1680 1690 1700  1710  1720 1730 1740Siècles :XVIe XVIIe  XVIIIe  XIXe XXeMillénaires :-Ier Ier  IIe  IIIe Chronologies thématiques Art Architecture, Arts...

 

You can help expand this article with text translated from the corresponding article in French. (March 2016) Click [show] for important translation instructions. View a machine-translated version of the French article. Machine translation, like DeepL or Google Translate, is a useful starting point for translations, but translators must revise errors as necessary and confirm that the translation is accurate, rather than simply copy-pasting machine-translated text into the English Wikipedi...

 

Member of the Parliament of England John Somerset or Somerseth (died 1454) was an English physician and administrator. He was born in London and attended Oxford University, but moved to Cambridge University to avoid the plague, graduating master in 1418. Thomas Beaufort, Duke of Exeter, appointed him master of the grammar school at Bury St Edmunds and just five years later he was named as a governor of a proposed joint college of medicine and surgery in London. Somerset worked on the college ...

Chinese 1979 foreign policy proposal The Three Links or Three Linkages (Chinese: 三通; pinyin: sān tōng) was a 1979 proposal from the National People's Congress of the People's Republic of China (PRC) to open up postal (simplified Chinese: 通邮; traditional Chinese: 通郵; pinyin: tōng yóu), transportation (especially airline) (通航; tōng háng), and trade (通商; tōng shāng) links between Mainland China and Taiwan,[1] with the goal of unifying Mainl...

 

Ruff degradation is a reaction used to shorten the open chain forms of monosaccharides.[1] It is functionally the reverse reaction of Kiliani-Fischer synthesis. In 1898, Otto Ruff published his work on the transformation of D-Glucose to D-Arabinose later called the Ruff degradation. In this reaction, D-Glucose is converted to D-Arabinose. In this reaction, the terminal aldehyde group is converted to a carboxylic acid group, using selective oxidation of the aldehyde using Bromine water...

 

Pharmaceutical company For the original US-based company, see Allergan, Inc. Allergan plcCompany typeSubsidiaryTraded asNYSE: AGNIndustryPharmaceuticalsPredecessorsAllergan, Inc. and Actavis before the 2015 tax inversion and mergerFoundedMay 16, 2013; 11 years ago (2013-05-16), upon the combination of Allergan Finance, LLC (Actavis) & Warner ChilcottMarch 17, 2015; 9 years ago (2015-03-17) renamed to Allergan Plc upon the merger of Allergan, Inc an...

В Википедии есть статьи о других людях с такой фамилией, см. Подколзин. Василий Подколзин Позиция Правый крайний нападающий Рост 185 см Вес 92 кг Хват левый Страна  Россия Дата рождения 24 июня 2001(2001-06-24) (22 года) Место рождения Москва, Россия Драфт НХЛ в 2019 году выбран в 1-м ...

 

Railway station in Merseyside, England Bidston Bidston station in 2007, seen from the footbridge, facing west towards LeasoweGeneral informationLocationBidston, WirralEnglandGrid referenceSJ283908Managed byMerseyrailTransit authorityMerseytravelPlatforms2Other informationStation codeBIDFare zoneB1ClassificationDfT category EKey dates2 July 1866Opened[1]4 July 1870Closed[1]1 August 1872Reopened[1]June 1890Closed[1]18 May 1896Reopened as a junction[1]1938...

 

  لمعانٍ أخرى، طالع دنيا (توضيح). هذه المقالة يتيمة إذ تصل إليها مقالات أخرى قليلة جدًا. فضلًا، ساعد بإضافة وصلة إليها في مقالات متعلقة بها. (ديسمبر 2015) دنيا ألبوم إستوديو لـنزيل عزمي الفنان نزيل عزمي تاريخ الإصدار 1 سبتمبر 2006 (منذ 17 سنة) التسجيل تسجيلات أوايكننغ النوع ال�...

Girl in Bahrain Politics of Bahrain Member State of the Arab League Constitution Human rights Monarchy King Hamad bin Isa Al Khalifa Cabinet Prime Minister Salman bin Hamad Al Khalifa Minister of Foreign Affairs Minister of Interior Minister of Justice Minister of Finance Minister of Housing National Assembly Consultative Council Chairman Council of Representatives Speaker Judiciary Elections Recent elections General: 2010201420182022 Referendums: 2001 (National Action Charter) Political par...

 

Фактор свёртывания крови XIIДоступные структурыPDB Поиск ортологов: PDBe, RCSBСписок идентификаторов PDB 4BDW, 4BDX ИдентификаторыСимвол F12 ; HAE3; HAEX; HAFВнешние ID OMIM: 610619 MGI: 1891012 HomoloGene: 425 ChEMBL: 2821 GeneCards: Ген F12номер EC 3.4.21.38Генная онтология Функция • serine-type endopeptidase activity • protein binding �...