Shakesort (Cocktailsort)

public override IEnumerable < T > Sort(IComparer < T > sortFunction, IEnumerable < T > collection) {
	List < T > objectList = collection.ToList();
	int endIndexLow = objectList.Count - 1;
	int endIndexHigh = 0;
	bool elementSwapped;

	do {
		elementSwapped = false;

		for (int x = endIndexHigh; x < endIndexLow; x++) {
			if (sortFunction.Compare(objectList[x], objectList[x + 1]) > 0) {
				elementSwapped = true;
				objectList.Swap(x, x + 1);
			}
		}

		endIndexLow--;
		if (!elementSwapped) break;

		elementSwapped = false;

		for (int y = endIndexLow; y > endIndexHigh; y--) {
			if (sortFunction.Compare(objectList[y], objectList[y - 1]) < 0) {
				elementSwapped = true;
				objectList.Swap(y, y - 1);
			}
		}

		endIndexHigh++;
	} while ( elementSwapped );

	return objectList;
}
public static void Swap(this IList list, int x, int y) {
	object buffer = list[y];
	list[y] = list[x];
	list[x] = buffer;
}

1
Hinterlasse einen Kommentar

Please Login to comment
  Subscribe  
newest oldest most voted
Notify of
trackback

[…] folgendem Beispiel werden von 100 bis 900 (in Einhundert Schritten) Daten (Zufallszahlen) mit dem Shakesort und dem Bubblesort sortiert. […]