Konstiga resultat av sorteringsalgoritmer

Permalänk

Konstiga resultat av sorteringsalgoritmer

Hej, Som jag förstått det så ska selection sort vara snabbare än insertion sort. Enligt mina resultat gäller motsatsen. Jag hoppas att någon skulle vilja titta igenom min kod och påpeka eventuella felaktigheter.

Selection sort

public override void Sort(int[] array) { SW1.Reset(); SW1.Start(); for (int i = 0; i < array.Length - 1; i++) { for (int p = i + 1; p < array.Length; p++) { if (array[i] > array[p]) { int temp = array[i]; array[i] = array[p]; array[p] = temp; } } } SW1.Stop(); TS = SW1.Elapsed; }

Insertion sort

public override void Sort(int[] array) { SW1.Reset(); SW1.Start(); int left = 0; while (left < array.Length - 1) { int value = array[left + 1]; for (int i = 0; i <= left; i++) { if (array[i] > value) { for (int p = left; p >= i; p--) { array[p + 1] = array[p]; } array[i] = value; break; } } left++; } SW1.Stop(); TS = SW1.Elapsed; }

Visa signatur

Macbook pro 13", 4gb ddr3, core2duo 2,53ghz, nvidia 9400m

Permalänk
Medlem
Skrivet av Torkelboy:

Hej, Som jag förstått det så ska selection sort vara snabbare än insertion sort. Enligt mina resultat gäller motsatsen.

Lite wikipedia utdrag:

Citat:

Selection sort - Wikipedia, the free encyclopedia

Selection sort is a sorting algorithm, specifically an in-place comparison sort. It has O(n2) 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.

Worst case performance: О(n²)
Best case performance: О(n²)
Average case performance: О(n²)

Citat:

Insertion sort - Wikipedia, the free encyclopedia

More efficient in practice than most other simple quadratic, i.e. O(n2) algorithms such as selection sort or bubble sort; the average running time is n2/4,[citation needed] and the running time is linear in the best case

Worst case performance: О(n²)
Best case performance: O(n)
Average case performance: О(n²)

Har inte kollat på din kod iom. detta.

Visa signatur

The difference between stupidity and genius - the latter has limits

Permalänk

Tack för det svaret, jag har varit och grötat efter svar på wikipedia, men uppenbarligen inte tillräckligt noggrant.

Visa signatur

Macbook pro 13", 4gb ddr3, core2duo 2,53ghz, nvidia 9400m