Swap-Sort

Swap-Sort

Swap-Sort ist ein Sortieralgorithmus, der ein Array aus paarweise verschiedenen Zahlen sortiert.

Inhaltsverzeichnis

Idee

Die Idee von Swap-Sort ist, von jedem Element eines Arrays A(1..n) die Anzahl m der kleineren Werte (die in A sind) zu zählen und das Element dann mit dem Element in A(m+1) zu vertauschen. Somit ist sichergestellt, dass das ausgetauschte Element bereits an der richtigen, also endgültigen Stelle steht.

Nachteil dieses Algorithmus ist, dass jedes Element nur einmal vorkommen darf, da sonst keine Terminierung erfolgt.

Prinzip

A ist ein Array mit n Elementen. Swap-Sort arbeitet in folgenden Schritten:

  • (1) Beginne mit i=1
  • (2) Zähle, wie viele Elemente kleiner als A(i) sind. Ist m diese Anzahl, so tausche A(i) mit A(m+1)
  • (3) Ist i=m+1, so erhöhe i um 1
  • (4) Ist i=n, so ist die Sortierung beendet - andernfalls gehe wieder zu Schritt 2

Beispiel

Es soll ein Array mit dem Inhalt [7|8|5|2|4|9|3|1] sortiert werden.


7 8 5 2 4 9 3 1   Mit dem Index 1 wird begonnen
^            
9 8 5 2 4 7 3 1   7 wurde mit A(5+1) getauscht
^         
1 8 5 2 4 7 3 9   9 wurde mit A(7+1) getauscht
^         
1 8 5 2 4 7 3 9   der Index wurde erhöht, da die Anzahl m der
  ^               kleineren Elemente von A(1) gleich dem Index-1 war         
1 3 5 2 4 7 8 9   8 wurde mit A(6+1) getauscht
  ^         
1 5 3 2 4 7 8 9
  ^         
1 4 3 2 5 7 8 9   der Index wurde erhöht, da die Anzahl m der
  ^               kleineren Elemente von A(2) gleich dem Index-1 war
1 2 3 4 5 7 8 9   ...usw.
    ^         
1 2 3 4 5 7 8 9
      ^         
1 2 3 4 5 7 8 9
        ^         
1 2 3 4 5 7 8 9
          ^         
1 2 3 4 5 7 8 9
            ^         
1 2 3 4 5 7 8 9  Das Array wurde komplett durchlaufen,
              ^  das Sortieren ist somit beendet

Komplexität

Die Komplexität von Swap-Sort kann mittels Landau-Symbol durch \mathcal{O}(n^2) ausgedrückt werden.

Implementierung

Ada

procedure swapsort (a: in out vector) is
 
z:integer;
 
        function ziel_pos(z:integer) return natural is
                anz:natural:=0;
        begin
                for i in a'range loop
                        if a(i) <= z then
                                anz:=anz+1;
                        end if;
                end loop;
                return anz;
        end
 
begin
        for index in a'range loop
                z:=ziel_pos(a(index));
                while z /= index loop
                        < vertausche a(index) mit a(z) >;
                        z:=ziel_pos(a(index));
                end loop;
        end loop;
end;

Haskell

swapSort x = swapSort' x 0 where
 
  swapSort' x i | i == length x = x
                | i == smaller  = swapSort' x (i+1)
                | otherwise     = swapSort' (swap x i smaller) i where
                    smaller = countSmaller x (x !! i)
 
  countSmaller = countSmaller' 0
  countSmaller n []     _ = n
  countSmaller n (x:xs) y | x < y     = countSmaller (n+1) xs y
                          | otherwise = countSmaller  n    xs y
 
  swap x i1 i2 = insert (remove (insert (remove x i1) e1 (i2-1)) i2) e2 i1 where
    e1 = x !! i1
    e2 = x !! i2
 
  remove (x:xs) 0 = xs
  remove (x:xs) n = x : remove xs (n-1)
  remove []     _ = error "Index zu groß"
 
  insert x      y 0 = y:x
  insert (x:xs) y n = x:insert xs y (n-1)
  insert []     _ _ = error "Index zu groß"

Java

public class SwapSorter {
 
    public void sort(int[] sortMe) {
 
        int startwert = 0;
 
 
 
 
        while (startwert < sortMe.length - 1) {
 
            int kleinere = countSmallerOnes(sortMe, startwert);
 
            if (kleinere > 0) {
                int tmp = sortMe[startwert];
                sortMe[startwert] = sortMe[startwert + kleinere];
                sortMe[startwert + kleinere] = tmp;                
            }
            else
            {
                startwert++;
            }
        }
    }
 
    private int countSmallerOnes(final int[] countHere, final int index) {
        int counter = 0;
        for (int i = index + 1; i < countHere.length; i++) {
            if (countHere[index] > countHere[i]) {
                counter++;
            }
        }
        return counter;
    }
 
    // Testmain
    public static void main(String[] args) {
 
        int[] a = {3, 7, 45, 1, 33, 5, 2, 9};
        System.out.print("unsorted: ");
        for (int i = 0; i < a.length; i++) {
            System.out.print(a[i] + "  ");
        }
        System.out.println();
        new SwapSorter().sort(a);
        System.out.print("sorted: ");
        for (int i = 0; i < a.length; i++) {
            System.out.print(a[i] + "  ");
        }
    }
}

Python

def swap_sort(sortme):
    index = 0
    while index < len(sortme) - 1:
        new_index = sum(x < sortme[index] for x in sortme)
        if index == new_index:
            index += 1
        else:
            sortme[index], sortme[new_index] = sortme[new_index], sortme[index]
    return sortme

Siehe auch


Wikimedia Foundation.

Игры ⚽ Поможем написать реферат

Schlagen Sie auch in anderen Wörterbüchern nach:

  • Swap (computer science) — For other uses of swap , see swap (disambiguation). In computer programming, the act of swapping two variables refers to mutually exchanging the values of the variables. Usually, this is done with the data in memory. For example, in a program,… …   Wikipedia

  • SWAP-200 — The Shedler Westen Assessment Procedure 200 (SWAP 200) is a research psychometric instrument that consists of a clinician report Q sort for assessing personality and personality pathology. An experienced clinician (usually a clinical psychologist …   Wikipedia

  • Bubble sort — Infobox Algorithm class=Sorting algorithm data=Array time= О(n²) space= О(n) total, O(1) auxiliary optimal=NoBubble sort is a simple sorting algorithm. It works by repeatedly stepping through the list to be sorted, comparing two items at a time… …   Wikipedia

  • Cocktail sort — Class Sorting algorithm Data structure Array Worst case performance О(n²) Best case performance O(n) …   Wikipedia

  • Comb sort — Class Sorting algorithm Data structure Array Worst case performance O(n log n)[1] …   Wikipedia

  • Selection sort — Infobox Algorithm class=Sorting algorithm data=Array time= О(n²) space= О(n) total, O(1) auxiliary optimal=Not usuallySelection sort is a sorting algorithm, specifically an in place comparison sort. It has O( n 2) complexity, making it… …   Wikipedia

  • Selection-Sort — Der Begriff Sortierlese oder Selection Sort (englisch selection »Auswahl«, to sort »sortieren«), auch MinSort (von Minimum) bzw. MaxSort (von Maximum), Selectsort oder ExchangeSort (AustauschSort) genannt, bezeichnet einen naiven… …   Deutsch Wikipedia

  • Selection Sort — Der Begriff Sortierlese oder Selection Sort (englisch selection »Auswahl«, to sort »sortieren«), auch MinSort (von Minimum) bzw. MaxSort (von Maximum), Selectsort oder ExchangeSort (AustauschSort) genannt, bezeichnet einen naiven… …   Deutsch Wikipedia

  • Odd–even sort — Example of odd even transposition sort sorting a list of random numbers. Class Sorting algorithm Data structure Array Worst case performance …   Wikipedia

  • Gnome sort — is a sorting algorithm which is similar to insertion sort, except that moving an element to its proper place is accomplished by a series of swaps, as in bubble sort. The name comes from the supposed behavior of the Dutch garden gnome in sorting a …   Wikipedia

Share the article and excerpts

Direct link
Do a right-click on the link above
and select “Copy Link”