ef:algorithmen:sortieralgorithmen

Dies ist eine alte Version des Dokuments!


Sortieralgorithmen in Python

# webtigerjython

from gpanel import *
import random 
import time

makeGPanel(0,600,0,400)

# Liste der Zahlen von 0 bis 99 in zufälliger Reihenfolge
zufallsListe = random.sample(range(0,100),100)

setColor("red")

#===============================================================
# Hilfsfunktion drawList, zeichnet ein Diagramm einer Liste
#===============================================================

def drawList(l,sleeptime):
    clear()
    x = 20
    lineWidth(5) 
    for i in l:
        line(x,30,x,i+30)
        x = x + 5
    time.sleep(sleeptime)

def bubbleSort(list1):
    for i in range(len(list1)-1,0,-1): #i läuft rückwärts
        for j in range(0,i,1):
            drawList(list1,0.01)
            if list1[j]>list1[j+1]:
                list1[j],list1[j+1] = list1[j+1],list1[j]

bubbleSort(zufallsListe)

#===============================================================
# Selection-Sort (Children-Sort)
#===============================================================

def getSmallestIndex(Liste1):
    smallestElement = Liste1[0]
    smallestIndex = 0
    for i in range(len(Liste1)):
        if Liste1[i] < smallestElement:
            smallestElement = Liste1[i]
            smallestIndex = i
    return smallestIndex
    
def selectionSort(Liste1):
    for i in range(len(Liste1)): 
        drawList(Liste1,0.1)
        index = getSmallestIndex(Liste1[i:]) + i 
        Liste1[i],Liste1[index] = Liste1[index],Liste1[i]

def nAreSmaller(list1, n):
    howMany = 0
    for i in list1:
        if (i<n):
            howMany = howMany + 1
    return howMany

def swapSort(list1):
    index = 0
    while index<len(list1):
        drawList(list1,0.1)
        element = list1[index]
        nSmaller = nAreSmaller(list1,element)
        list1[index],list1[nSmaller] = list1[nSmaller],list1[index]
        if (index == nSmaller):
            index = index + 1

def merge(l1,l2):
    c = []
    while len(l1) != 0 and len(l2) != 0:
        if l1[0] < l2[0]:
            c.append(l1[0])
            l1.remove(l1[0])
        else:
            c.append(l2[0])
            l2.remove(l2[0])
    if len(l1) == 0:
        c += l2
    else:
        c += l1
    return c

def mergesort(list1):
    if len(list1) == 0 or len(list1) == 1:
        return list1
    else:
        middle = int(len(list1)/2)
        a = mergesort(list1[:middle])
        b = mergesort(list1[middle:])
        return merge(a,b)

  • ef/algorithmen/sortieralgorithmen.1713445552.txt.gz
  • Zuletzt geändert: 2024/04/18 15:05
  • von lehmannr