Thursday 1 June 2017

Knuth Gleitender Durchschnitt


1.5 Input und Output In diesem Abschnitt erweitern wir die Menge der einfachen Abstraktionen (Kommandozeilen-Input und Standard-Ausgabe), die wir als Schnittstelle zwischen unseren Java-Programmen und der Außenwelt verwendet haben, um Standard-Input enthalten. Standardzeichnung. Und Standard-Audio. Die Standard-Eingabe macht es uns bequem, Programme zu schreiben, die beliebige Mengen an Input verarbeiten und mit unseren Programmen interagieren. Standard-Draw macht es möglich, dass wir mit Grafik arbeiten und Standard-Audio fügt Sound hinzu. Vogelperspektive. Ein Java-Programm nimmt Eingabewerte von der Befehlszeile und druckt eine Zeichenfolge als Ausgabe. Standardmäßig sind sowohl Befehlszeilenargumente als auch Standardausgabe einer Anwendung zugeordnet, die Befehle enthält, die wir als Terminalfenster bezeichnen. Hier finden Sie einige Anweisungen zur Verwendung der Befehlszeile auf Ihrem System. Mac middot Windows middot Linux Befehlszeilenargumente. Alle unsere Klassen haben eine main () Methode, die ein String Array Args als Argument nimmt. Dieses Array ist die Folge von Befehlszeilenargumenten, die wir eingeben. Wenn wir beabsichtigen, dass ein Argument eine Zahl ist, müssen wir eine Methode wie Integer. parseInt () verwenden, um sie von String in den entsprechenden Typ zu konvertieren. Standardausgabe. Um die Ausgabewerte in unseren Programmen zu drucken, verwenden wir System. out. println (). Java sendet die Ergebnisse an einen abstrakten Stream von Zeichen, die als Standardausgabe bekannt sind. Standardmäßig verbindet das Betriebssystem die Standardausgabe mit dem Terminalfenster. Die gesamte Ausgabe in unseren Programmen ist bisher im Terminalfenster erschienen. RandomSeq. java verwendet dieses Modell: Es nimmt ein Kommandozeilenargument n und druckt zur Standardausgabe eine Folge von n Zufallszahlen zwischen 0 und 1. Um unser Programmiermodell zu vervollständigen, fügen wir folgende Bibliotheken hinzu: Standardeingabe. Lesen Sie Zahlen und Strings vom Benutzer. Standardzeichnung. Plot Grafiken. Standard-Audio. Klang erzeugen Standardausgabe. Javas System. out. print () und System. out. println () Methoden implementieren die grundlegende Standardausgabe Abstraktion, die wir benötigen. Trotzdem verwenden wir ähnliche Methoden, die in unserer StdOut-Bibliothek definiert sind: Javas print () und println () Methoden, die Sie haben, um die Standard-Input - und Standard-Ausgabe einheitlich zu behandeln (und einige technische Verbesserungen vorzulegen) Verwendet haben. Die printf () - Methode gibt uns mehr Kontrolle über das Aussehen der Ausgabe. Formatierte Druckgrundlagen. In seiner einfachsten Form nimmt printf () zwei Argumente an. Das erste Argument wird als Formatzeichenfolge bezeichnet. Es enthält eine Umwandlungsspezifikation, die beschreibt, wie das zweite Argument in einen String für die Ausgabe konvertiert werden soll. Format-Strings beginnen mit und enden mit einem Ein-Buchstaben-Umwandlungscode. Die folgende Tabelle fasst die am häufigsten verwendeten Codes zusammen: Format string. Der Formatstring kann Zeichen zusätzlich zu denen für die Umwandlungsspezifikation enthalten. Die Conversion-Spezifikation wird durch den Argumentwert ersetzt (in einen String wie angegeben umgewandelt) und alle restlichen Zeichen werden an die Ausgabe übergeben. Mehrere Argumente Die Funktion printf () kann mehr als zwei Argumente ausführen. In diesem Fall hat der Formatstring eine zusätzliche Konvertierungsspezifikation für jedes weitere Argument. Hier ist mehr Dokumentation auf printf format string syntax. Standard input. Unsere StdIn-Bibliothek nimmt Daten aus einem Standard-Eingangsstrom auf, der eine Folge von durch Whitespace getrennten Werten enthält. Jeder Wert ist ein String oder ein Wert aus einem der Javas-Primitivtypen. Eines der Hauptmerkmale des Standard-Eingangsstroms ist, dass Ihr Programm Werte verbraucht, wenn es sie liest. Sobald Ihr Programm einen Wert gelesen hat, kann es nicht wieder gesichert werden und es nochmal lesen. Die Bibliothek wird durch die folgende API definiert: Wir betrachten nun mehrere Beispiele im Detail. Eingabe eingeben. Wenn du den Java-Befehl benutzt, um ein Java-Programm von der Befehlszeile aus aufzurufen, machst du eigentlich drei Dinge: (1) Ausgabe eines Befehls zum Starten des Programms, (2) Festlegen der Werte der Befehlszeilenargumente und ( 3) beginnen, den Standard-Eingangsstrom zu definieren. Die Zeichenfolge, die Sie im Terminalfenster nach der Befehlszeile eingeben, ist der Standard-Eingangsstrom. Zum Beispiel nimmt AddInts. java ein Befehlszeilenargument n ein. Dann liest man n Zahlen aus der Standard-Eingabe und fügt sie hinzu und druckt das Ergebnis zur Standardausgabe: Eingabeformat. Wenn Sie abc oder 12.2 oder true eingeben, wenn StdIn. readInt () ein int erwartet. Dann wird es mit einer InputMismatchException antworten. StdIn behandelt Strings von aufeinanderfolgenden Whitespace-Zeichen als identisch mit einem Leerzeichen und erlaubt Ihnen, Ihre Zahlen mit solchen Strings zu begrenzen. Interaktive Benutzereingaben. TwentyQuestions. java ist ein einfaches Beispiel für ein Programm, das mit seinem Benutzer interagiert. Das Programm erzeugt eine zufällige Ganzzahl und gibt dann Hinweise auf einen Benutzer, der versucht, die Nummer zu erraten. Der grundlegende Unterschied zwischen diesem Programm und anderen, die wir geschrieben haben, ist, dass der Benutzer die Möglichkeit hat, den Kontrollfluss zu ändern, während das Programm ausgeführt wird. Verarbeiten eines beliebigen Eingangsstroms. Typischerweise sind die Eingangsströme endlich: Ihr Programm marschiert durch den Eingabestrom und verbraucht Werte, bis der Stream leer ist. Aber es gibt keine Beschränkung der Größe des Eingangsstroms. Average. java liest in einer Folge von reellen Zahlen aus der Standard-Eingabe und druckt ihren Durchschnitt. Umleitung und Rohrleitung. Für viele Anwendungen ist die Eingabe von Eingabedaten als Standard-Eingangsstrom aus dem Terminal-Fenster unhaltbar, da damit unsere Programme die Leistungsfähigkeit um die Datenmenge beschränken, die wir eingeben können. In ähnlicher Weise wollen wir oft die auf dem Standardausgangsstrom gedruckten Informationen für spätere Verwendung speichern. Wir können Betriebssystemmechanismen verwenden, um beide Probleme zu lösen. Umleiten der Standardausgabe in eine Datei. Durch Hinzufügen einer einfachen Anweisung zu dem Befehl, der ein Programm aufruft, können wir seine Standardausgabe in eine Datei umleiten, entweder für permanente Speicherung oder für die Eingabe zu einem anderen Programm zu einem späteren Zeitpunkt. Beispielsweise gibt der Befehl an, dass der Standardausgabestream nicht im Terminalfenster gedruckt werden soll, sondern stattdessen in eine Textdatei mit dem Namen data. txt geschrieben werden soll. Jeder Aufruf von StdOut. print () oder StdOut. println () fügt Text am Ende dieser Datei hinzu. In diesem Beispiel ist das Endergebnis eine Datei, die 1.000 zufällige Werte enthält. Umleiten der Standardausgabe aus einer Datei. Ebenso können wir die Standard-Eingabe umleiten, so dass StdIn Daten aus einer Datei anstelle des Terminalfensters liest. Zum Beispiel gibt der Befehl eine Sequenz von Zahlen aus der Datei data. txt und berechnet ihren Mittelwert. Insbesondere ist das lt-Symbol eine Richtlinie, um den Standard-Eingangsstrom zu implementieren, indem er aus der Datei data. txt liest, anstatt darauf zu warten, dass der Benutzer etwas in das Terminalfenster eintippt. Wenn das Programm StdIn. readDouble () aufruft. Das Betriebssystem liest den Wert aus der Datei. Diese Möglichkeit, die Standard-Eingabe aus einer Datei umzuleiten, ermöglicht es uns, riesige Mengen an Daten aus jeder beliebigen Quelle mit unseren Programmen zu verarbeiten, die nur durch die Größe der Dateien, die wir speichern können, begrenzt sind. Verbinden von zwei Programmen. Die flexibelste Art, die Standard-Input - und Standard-Output-Abstraktionen zu implementieren, besteht darin, festzulegen, dass sie durch eigene Programme implementiert werden. Dieser Mechanismus heißt Pipeline. Beispielsweise zeigen die folgenden Befehle an, dass die Standardausgabe für RandomSeq und der Standard-Eingangsstrom für Average der gleiche Stream sind. Filter. Für viele gemeinsame Aufgaben ist es praktisch, an jedes Programm als Filter zu denken, das einen Standard-Eingangsstrom in einen beliebigen Ausgabestream in irgendeiner Weise umwandelt. RangeFilter. java nimmt zwei Befehlszeilenargumente und druckt auf Standardausgabe diese Zahlen von der Standard-Eingabe Die in den angegebenen Bereich fallen. Ihr Betriebssystem bietet auch eine Reihe von Filtern. Zum Beispiel stellt der Sortierfilter die Zeilen auf Standard-Eingabe in sortierter Reihenfolge: Ein weiterer nützlicher Filter ist mehr. Die Daten aus der Standard-Eingabe liest und zeigt sie in Ihrem Terminal-Fenster ein Screenful zu einer Zeit. Zum Beispiel, wenn Sie eingeben, sehen Sie so viele Zahlen wie in Ihrem Terminal-Fenster passen, aber mehr wird auf Sie warten, um die Leertaste zu schlagen, bevor Sie jede nachfolgende Screenful. Standardzeichnung. Jetzt stellen wir eine einfache Abstraktion zur Herstellung von Zeichnungen als Ausgabe vor. Wir stellen uns eine abstrakte Zeichnungsvorrichtung vor, die in der Lage ist, Linien und Punkte auf einer zweidimensionalen Leinwand zu zeichnen. Das Gerät ist in der Lage, auf die Befehle zu antworten, die unsere Programme in Form von Anrufen zu statischen Methoden in StdDraw ausgeben. Die primäre Schnittstelle besteht aus zwei Arten von Methoden: Zeichnen von Befehlen, die dazu führen, dass das Gerät eine Aktion ausführt (z. B. Zeichnen einer Linie oder Zeichnen eines Punktes) und Kontrollbefehle, die Parameter wie die Stiftgröße oder die Koordinatenwaagen festlegen. Grundlegende Zeichnungsbefehle. Wir betrachten zunächst die Zeichnungsbefehle: Diese Methoden sind fast selbstdokumentierend: StdDraw. line (x0, y0, x1, y1) zeichnet ein Geradensegment, das den Punkt (x 0. y 0) mit dem Punkt (x 1 1). StdDraw. point (x, y) zeichnet einen Punkt, der auf den Punkt (x. Y) zentriert ist. Die Standard-Koordinatenskala ist das Einheitsplatz (alle x - und y-Koordinaten zwischen 0 und 1). Die Standardimplementierung zeigt die Leinwand in einem Fenster auf Ihrem Computerbildschirm an, mit schwarzen Linien und Punkten auf weißem Hintergrund. Ihre erste Zeichnung. Die HelloWorld für Grafikprogrammierung mit StdDraw ist ein Dreieck mit einem Punkt innen zu zeichnen. Triangle. java erreicht dies mit drei Anrufen zu StdDraw. line () und einem Aufruf zu StdDraw. point (). Steuerbefehle. Die Standard-Canvas-Größe ist 512-mal-512 Pixel und das Standard-Koordinatensystem ist das Einheits-Quadrat, aber wir wollen oft Plots auf verschiedenen Skalen zeichnen. Auch wollen wir oft Liniensegmente unterschiedlicher Dicke oder Punkte unterschiedlicher Größe vom Standard zeichnen. Um diesen Bedürfnissen gerecht zu werden, hat StdDraw die folgenden Methoden: Beispielsweise setzt die Zwei-Call-Sequenz die Zeichenkoordinaten innerhalb eines Begrenzungsfeldes, dessen untere linke Ecke bei (x 0 y 0) liegt und deren obere rechte Ecke ist Bei (x 1, y 1). Filtern von Daten zu einer Standardzeichnung. PlotFilter. java liest eine Folge von Punkten, die durch (x. Y) Koordinaten von der Standard-Eingabe definiert sind, und zeichnet einen Punkt an jedem Punkt. Es nimmt die Konvention an, dass die ersten vier Zahlen auf der Standard-Eingabe die Begrenzungsbox angeben, damit sie das Diagramm skalieren kann. Plotten eines Funktionsgraphen FunctionGraph. java zeichnet die Funktion y sin (4 x) sin (20 x) im Intervall (0, pi) auf. Es gibt unendlich viele Punkte im Intervall, also müssen wir mit der Auswertung der Funktion an einer endlichen Anzahl von Punkten innerhalb des Intervalls zu tun haben. Wir probieren die Funktion aus, indem wir einen Satz von x-Werten auswählen und dann y-Werte auswerten, indem wir die Funktion bei jedem x-Wert auswerten. Das Plotten der Funktion durch das Verbinden von aufeinanderfolgenden Punkten mit Linien erzeugt eine sogenannte stückweise lineare Näherung. Ausrichtung und gefüllte Formen. StdDraw enthält auch Methoden, um Kreise, Rechtecke und beliebige Polygone zu zeichnen. Jede Form definiert eine Kontur. Wenn der Methodenname nur der Formname ist, wird dieser Umriß durch den Zeichenstift verfolgt. Wenn der Methodenname mit gefüllt beginnt. Die Namensform wird stattdessen fest gefüllt, nicht verfolgt. Die Argumente für den Kreis () definieren einen Kreis des Radius r die Argumente für Quadrat () definieren ein Quadrat der Seitenlänge 2r auf den gegebenen Punkt zentriert und die Argumente für Polygon () definieren ein Abfolge von Punkten, die wir durch Linien verbinden, einschließlich eines vom letzten Punkt bis zum ersten Punkt. Text und Farbe. Um verschiedene Elemente in Ihren Zeichnungen zu annotieren oder hervorzuheben, enthält StdDraw Methoden zum Zeichnen von Text, zum Einstellen der Schriftart und zum Einstellen der Tinte in den Stift. In diesem Code sind java. awt. Font und java. awt. Color Abstraktionen, die implementiert sind Mit nicht-primitiven Typen, die Sie in Abschnitt 3.1 erfahren werden. Bis dahin verlassen wir die Details an StdDraw. Die Standard-Tintenfarbe ist schwarz, die Standardschriftart ist eine 16-Punkt-Serif-Schriftart. Doppelpufferung StdDraw unterstützt eine leistungsstarke Computergrafik-Funktion, die als Doppelpufferung bekannt ist. Wenn die doppelte Pufferung durch Aufruf von enableDoubleBuffering () aktiviert ist. Alle zeichnung findet auf der offscreen canvas statt. Die Offscreen-Leinwand wird nicht angezeigt, sie existiert nur im Computerspeicher. Erst wenn du Show () nennst, wird deine Zeichnung aus der Offscreen-Leinwand auf die Leinwand Leinwand kopiert. Wo es im Standard-Zeichnungsfenster angezeigt wird. Du kannst an doppelte Pufferung denken, indem du alle Zeilen, Punkte, Formen und Texte sammelt, die du ihm erzählst, und sie alle gleichzeitig zu ziehen, auf Wunsch. Ein Grund für die doppelte Pufferung ist für die Effizienz bei der Durchführung einer großen Anzahl von Zeichnungsbefehlen. Computeranimationen Unser wichtigster Einsatz von Doppelpufferung ist die Herstellung von Computeranimationen. Wo wir die Illusion der Bewegung durch schnelles Anzeigen von statischen Zeichnungen schaffen. Wir können Animationen produzieren, indem wir die folgenden vier Schritte wiederholen: Löschen Sie die offscreen Leinwand. Zeichnen von Objekten auf dem Offscreen Kopieren Sie die Offscreen-Leinwand auf die Leinwand. Warten Sie kurz. Zur Unterstützung dieser Schritte hat das StdDraw mehrere Methoden: Das Hallo, World Programm für Animation ist es, einen schwarzen Ball zu produzieren, der sich auf der Leinwand zu bewegen scheint und von der Grenze nach den Gesetzen der elastischen Kollision abprallt. Angenommen, der Ball ist an der Position (x. Y) und wir wollen den Eindruck erwecken, dass er sich in eine neue Position bewegt, sagen wir (x 0,01, y 0,02). Wir tun dies in vier Schritten: Löschen Sie die offscreen Leinwand zu weiß. Zeichnen Sie einen schwarzen Ball an der neuen Position auf der Offscreen-Leinwand. Kopiere die offscreen-Leinwand auf die Leinwand. Warten Sie kurz. Um die Illusion der Bewegung zu schaffen, verbreitet BouncingBall. java diese Schritte für eine ganze Sequenz von Positionen des Balles. Bilder. Unsere Standard-Draw-Bibliothek unterstützt Zeichnungsbilder sowie geometrische Formen. Der Befehl StdDraw. picture (x, y, Dateiname) zeichnet das Bild im angegebenen Dateinamen (entweder JPEG, GIF oder PNG-Format) auf der Leinwand, zentriert auf (x, y). BouncingBallDeluxe. java illustriert ein Beispiel, wo der Hüpfball durch ein Bild eines Tennisballs ersetzt wird. Benutzerinteraktion. Unsere Standard-Draw-Bibliothek enthält auch Methoden, so dass der Benutzer mit dem Fenster mit der Maus interagieren kann. Ein erstes Beispiel. MouseFollower. java ist die HelloWorld der Maus-Interaktion. Es zieht einen blauen Ball, zentriert auf die Lage der Maus. Wenn der Benutzer die Maustaste gedrückt hält, wechselt der Ball von blau nach cyan. Ein einfacher Attraktor. OneSimpleAttractor. java simuliert die Bewegung eines blauen Balles, der von der Maus angezogen wird. Es macht auch eine Schleppkraft aus. Viele einfache Attraktoren. SimpleAttractors. java simuliert die Bewegung von 20 blauen Kugeln, die von der Maus angezogen werden. Es macht auch eine Schleppkraft aus. Wenn der Benutzer klickt, verteilen sich die Kugeln nach dem Zufallsprinzip. Entspringt Springs. java implementiert ein Federsystem. Standard-Audio. StdAudio ist eine Bibliothek, die Sie zum Abspielen und Manipulieren von Audiodateien verwenden können. Es erlaubt Ihnen zu spielen, zu manipulieren und zu synthetisieren. Wir stellen einige grundlegende Konzepte hinter einem der ältesten und wichtigsten Bereiche der Informatik und des wissenschaftlichen Rechnens vor: Digitale Signalverarbeitung. Konzert A. Konzert A ist eine Sinuswelle, skaliert, um mit einer Frequenz von 440 mal pro Sekunde zu oszillieren. Die Funktion sin (t) wiederholt sich einmal alle 2pi Einheiten auf der x-Achse, also wenn wir t in Sekunden messen und die Funktion sin (2pi t mal 440) zeichnen, erhalten wir eine Kurve, die 440 mal pro Sekunde oszilliert. Die Amplitude (y-Wert) entspricht der Lautstärke. Wir nehmen an, dass es zwischen minus1 und 1 skaliert ist. Weitere Anmerkungen. Eine einfache mathematische Formel charakterisiert die anderen Noten auf der chromatischen Skala. Sie sind gleichmäßig auf eine logarithmische (Basis 2) Skala geteilt: Es gibt zwölf Noten auf der chromatischen Skala, und wir erhalten die i-te Anmerkung über einer gegebenen Note, indem wir ihre Frequenz mit der (i 12) th Macht von 2 multiplizieren. Wenn du Doppelt oder halbieren Sie die Frequenz, Sie bewegen sich nach oben oder unten eine Oktave auf der Skala. Zum Beispiel 880 Hertz ist eine Oktave über Konzert A und 110 Hertz ist zwei Oktaven unter dem Konzert A. Sampling. Für den digitalen Ton repräsentieren wir eine Kurve, indem wir sie in regelmäßigen Abständen probieren, und zwar genau wie bei der Darstellung von Funktionsgraphen. Wir probieren genügend oft, dass wir eine genaue Darstellung der curvemdasha weit verbreitet Probenahme Rate ist 44.100 Proben pro Sekunde. Es ist so einfach: Wir stellen Ton als Array von Zahlen dar (reale Zahlen, die zwischen minus1 und 1 liegen). Zum Beispiel spielt das folgende Codefragment Konzert A für 10 Sekunden. Spiele diese Melodie. PlayThatTune. java ist ein Beispiel, das zeigt, wie leicht wir mit StdAudio Musik erstellen können. Es nimmt Notizen von der Standard-Eingabe, indiziert auf der chromatischen Skala von Konzert A, und spielt sie auf Standard-Audio. Schreiben Sie ein Programm MaxMin. java, das Integers (so viele wie der Benutzer eingibt) aus der Standard-Eingabe und druckt die maximale und minimale Werte. Schreiben Sie ein Programm Stats. java, das ein Integer-Befehlszeilenargument n nimmt. Liest n Gleitkommazahlen von der Standard-Eingabe und druckt ihren Mittelwert (Mittelwert) und probiert die Standardabweichung (Quadratwurzel der Summe der Quadrate ihrer Differenzen vom Durchschnitt, dividiert durch n minus1). Schreiben Sie ein Programm LongestRun. java, das in einer Folge von ganzen Zahlen liest und druckt sowohl die Ganzzahl, die in einem längsten aufeinander folgenden Lauf und die Länge des Laufs erscheint. Wenn zum Beispiel der Eingang 1 2 2 1 5 1 1 7 7 7 7 1 1 ist. Dann sollte dein Programm am längsten laufen: 4 aufeinanderfolgende 7s. Schreiben Sie ein Programm WordCount. java, das Text aus der Standard-Eingabe liest und die Anzahl der Wörter im Text ausdruckt. Für die Zwecke dieser Übung ist ein Wort eine Folge von Nicht-Whitespace-Charakteren, die von Leerzeichen umgeben ist. Schreiben Sie ein Programm Closest. java, das drei Gleitkomma-Befehlszeilenargumente (x, y, z) annimmt, liest aus der Standard-Eingabe eine Folge von Punktkoordinaten ((xi, yi, zi)) und druckt die Koordinaten des Punktes Am nächsten ((x, y, z)). Erinnern Sie sich, dass das Quadrat des Abstandes zwischen ((x, y, z)) und ((xi, yi, zi)) ((x - xi) 2 (y - yi) 2 (z - zi) 2) ist. Für die Effizienz, verwenden Sie nicht Math. sqrt () oder Math. pow (). Angesichts der Positionen und Massen einer Folge von Objekten, schreiben Sie ein Programm, um ihre Mitte-of-Masse oder Schwerpunkt zu berechnen. Der Schwerpunkt ist die durchschnittliche Position der n Objekte, gewichtet nach Masse. Wenn die Positionen und Massen durch (xi yi mi) gegeben sind, dann ist der Schwerpunkt (x. Y. m) gegeben durch: Schreiben Sie ein Programm Centroid. java, das in einer Folge von Positionen und Massen liest (xi yi. Mi) von der Standard-Eingabe und druckt den Schwerpunkt (x. Y) aus. Hinweis. Modelliere dein Programm nach Average. java. Schreiben Sie ein Programm Checkerboard. java, das ein Befehlszeilenargument n annimmt und ein n-by-n Schachbrett mit roten und schwarzen Quadraten zeichnet. Farbe links unten links rot. Schreiben Sie ein Programm Rose. java, das ein Kommandozeilenargument n annimmt und eine Rose mit n Blütenblättern (wenn n ungerade ist) oder 2n Blütenblättern (wenn n gerade ist), indem Sie die Polarkoordinaten (r, theta) der Funktion r zeichnen Sin (n mal theta) für theta von 0 bis 2pi radiant. Unten ist die gewünschte Ausgabe für n 4, 7 und 8. Schreiben Sie ein Programm Banner. java, das einen String s aus der Kommandozeile nimmt und es im Banner-Stil auf dem Bildschirm anzeigt, von links nach rechts bewegt und zurück zum Anfang wickelt Der Saite, da das Ende erreicht ist. Fügen Sie ein zweites Befehlszeilenargument hinzu, um die Geschwindigkeit zu steuern. Schreiben Sie ein Programm Circles. java, das gefüllte Kreise von zufälliger Größe an zufälligen Positionen in der Einheit Quadrat, produziert Bilder wie die unten. Ihr Programm sollte vier Befehlszeilenargumente nehmen: die Anzahl der Kreise, die Wahrscheinlichkeit, dass jeder Kreis schwarz ist, der minimale Radius und der maximale Radius. Kreative Übungen Spirographs. Schreiben Sie ein Programm Spirograph. java, das drei Befehlszeilenargumente R, r und a nimmt und den resultierenden Spirograph zeichnet. Ein Spirograph (technisch eine Epizykloide) ist eine Kurve, die durch das Rollen eines Kreisradius r um einen größeren festen Kreis oder Radius R gebildet wird. Wenn der Stiftversatz von der Mitte des Rollkreises (ra) ist, dann ist die Gleichung der resultierenden Kurve zum Zeitpunkt t ist gegeben von solchen Kurven wurden von einem meistverkauften Spielzeug, das Scheiben mit Zahnradzähne an den Rändern und kleinen Löchern, die Sie einen Stift in Spur Spirographen zu verfolgen, Für einen dramatischen 3d-Effekt zeichnen Sie ein kreisförmiges Bild, z. B. Earth. gif statt eines Punktes, und zeige es im Laufe der Zeit. Heres ein Bild des resultierenden Spirographen, wenn R 180, r 40 und ein 15. Uhr. Schreiben Sie ein Programm Clock. java, das eine Animation der zweiten, Minuten - und Stundenzeiger einer analogen Uhr anzeigt. Verwenden Sie die Methode StdDraw. show (1000), um die Anzeige etwa einmal pro Sekunde zu aktualisieren. Hinweis. Dies kann eine der seltenen Zeiten sein, wenn man den Betreiber mit einem Doppelten benutzen möchte - es funktioniert so, wie man es erwarten würde. Oszilloskop. Schreiben Sie ein Programm Oscilloscope. java, um die Ausgabe eines Oszilloskops zu simulieren und produzieren Lissajous Muster. Diese Muster sind nach dem französischen Physiker Jules A. Lissajous benannt, der die Muster untersucht hat, die entstehen, wenn zwei gegenseitig senkrechte periodische Störungen gleichzeitig auftreten. Nehmen wir an, dass die Eingänge sinusförmig sind, so dass die folgenden parametrischen Gleichungen die Kurve beschreiben: Nehmen Sie die sechs Parameter A x. W x Die Steuer . Theta y W y Und theta y von der Kommandozeile aus. Zum Beispiel hat das erste Bild unten Ax Ay 1, w x 2, w y 3, theta x 20 Grad, theta y 45 Grad. Der andere hat Parameter (1, 1, 5, 3, 30, 45) Webübungen Wort - und Zeilenzahl. Ändern Sie WordCount. java so, dass in Text aus Standard-Eingabe liest und druckt die Anzahl der Zeichen, Wörter und Zeilen im Text. Niederschlagsproblem Schreiben Sie ein Programm Rainfall. java, das in nichtnegativen Ganzzahlen (was Niederschlag repräsentiert) ein zu einer Zeit bis 999999 eingegeben wird, und dann druckt den Durchschnitt des Wertes (nicht einschließlich 999999). Duplikate entfernen Schreiben Sie ein Programm Duplicates. java, das in einer Folge von Ganzzahlen liest und druckt die Ganzzahlen, außer dass es wiederholte Werte entfernt, wenn sie nacheinander erscheinen. Zum Beispiel, wenn die Eingabe 1 2 2 1 5 1 1 7 7 7 7 1 1 ist, sollte Ihr Programm ausdrucken 1 2 1 5 1 7 1. Lauflängencodierung. Schreiben Sie ein Programm RunLengthEncoder. java, das eine Binäreingabe mit Lauflängencodierung kodiert. Schreiben Sie ein Programm RunLengthDecoder. java, das eine lauflängencodierte Nachricht decodiert. Kopf und Schwanz Schreiben Sie Programme Head. java und Tail. java, die einen Integer-Befehlszeileneingang N nehmen und die ersten oder letzten N Zeilen der angegebenen Datei ausdrucken. (Drucken Sie die ganze Datei aus, wenn es darum besteht Beispielsweise wird die Nachricht VENI, VIDI, VICI in YHQL, YLGL, YLFL konvertiert. Schreiben Sie ein Programm Caesar. java, das ein Befehlszeilenargument k annimmt und eine Caesar-Chiffre mit Shift k an anwendet Eine Sequenz von Briefen, die von der Standard-Eingabe gelesen werden. Wenn ein Brief kein Großbuchstabe ist, schreib es einfach aus. Cäsar-Chiffrier-Decodierung Wie würdest du eine Nachricht verschlüsseln, die mit einem Caesar-Chiffre-Hinweis verschlüsselt ist, solltest du keinen Code schreiben Paritätsprüfung Eine Boolesche Matrix hat die Paritätseigenschaft, wenn jede Zeile und jede Spalte eine gerade Summe hat. Dies ist eine einfache Art von Fehlerkorrekturcode, denn wenn ein Bit in der Übertragung beschädigt ist (Bit wird von 0 auf 1 oder von verschoben 1 bis 0) es kann erkannt und repariert werden Heres eine 4 x 4 Eingabedatei, die die Paritätseigenschaft hat: Schreiben Sie ein Programm ParityCheck. java, das eine Integer N als Kommandozeileneingabe annimmt und in einem N-by-N Boolean liest Matrix aus der Standard-Eingabe und gibt an, ob (i) die Matrix die Paritätseigenschaft hat oder (ii) anzeigt, welches einzelne beschädigte Bit (i, j) umgedreht werden kann, um die Paritätseigenschaft wiederherzustellen, oder (iii) zeigt an, dass die Matrix war Beschädigt (mehr als zwei Bits müssen geändert werden, um die Paritätseigenschaft wiederherzustellen). Verwenden Sie so wenig interne Speicher wie möglich. Hinweis: Sie müssen nicht einmal die Matrix-Takagis-Funktion speichern. Plot Takagis Funktion: überall stetig, nirgendwo differenzierbar. Tramperproblem Sie interviewen N Kandidaten für die alleinige Position von American Idol. Jede Minute bekommst du einen neuen Kandidaten zu sehen, und du hast eine Minute zu entscheiden, ob oder nicht zu erklären, dass Person die American Idol. Sie können nicht Ihre Meinung ändern, sobald Sie beenden Interview mit dem Kandidaten. Angenommen, Sie können jeden Kandidaten sofort mit einer einzigen realen Zahl zwischen 0 und 1 bewerten, aber natürlich wissen Sie nicht die Bewertung der Kandidaten noch nicht gesehen. Entwerfen Sie eine Strategie und schreiben Sie ein Programm AmericanIdol, das mindestens eine Chance hat, den besten Kandidaten auszuwählen (vorausgesetzt, die Kandidaten kommen in zufälliger Reihenfolge), lesen Sie die 500 Datenwerte aus der Standard-Eingabe. Lösung: Interview für N2 Minuten und notiere die Bewertung des bisher besten Kandidaten. In den nächsten N2 Minuten, wähle den ersten Kandidaten, der eine höhere Bewertung als die aufgezeichnete hat. Dies ergibt mindestens eine 25 Chance, da Sie den besten Kandidaten bekommen, wenn der zweitbeste Kandidat in den ersten N2 Minuten ankommt und der beste Kandidat in den letzten N2 Minuten ankommt. Dies kann leicht auf 1e 0,36788 verbessert werden, indem im Wesentlichen die gleiche Strategie verwendet wird, aber Umschalten zur Zeit Ne. Verschachtelte Diamanten. Schreiben Sie ein Programm Diamonds. java, das eine Befehlszeile Eingabe N und Plots N verschachtelten Quadrate und Diamanten nimmt. Unten ist die gewünschte Ausgabe für N 3, 4 und 5. Regelmäßige Polygone. Erstellen Sie eine Funktion, um einen N-Gon zu zeichnen, zentriert auf (x, y) der Größenlänge s. Verwenden Sie die Funktion, um verschachtelte Polygone wie das Bild unten zu zeichnen. Gewölbte Quadrate Schreiben Sie ein Programm BulgingSquares. java, das die folgende optische Täuschung von Akiyoshi Kitaoka zieht. Das Zentrum scheint sich nach außen zu wölben, obwohl alle Quadrate gleich groß sind. Spiralende Mäuse Angenommen, N-Mäuse, die auf den Ecken eines regulären Polygons mit N-Seiten beginnen, und jeder Kopf in Richtung der nächsten anderen Maus (im Gegenuhrzeigersinn), bis sie alle treffen. Schreiben Sie ein Programm, um die logarithmischen Spiralpfade zu zeichnen, die sie durch Zeichnen von verschachtelten N-Gons, die in dieser Animation gedreht und geschrumpft sind. Spiral. Schreiben Sie ein Programm, um eine Spirale wie die unten zu zeichnen. Globus. Schreiben Sie ein Programm Globe. java, das ein echtes Kommandozeilen-Argument alpha nimmt und ein globeartiges Muster mit Parameter alpha zeichnet. Zeichnen Sie die Polarkoordinaten (r, theta) der Funktion f (theta) cos (alpha mal theta) für theta von 0 bis 7200 Grad. Unten ist die gewünschte Ausgabe für Alpha 0,8, 0,9 und 0,95. Zeichenketten zeichnen Schreiben Sie ein Programm RandomText. java, das einen String s und eine Ganzzahl N als Kommandozeileneingaben einnimmt und die Zeichenfolge N mal an einer zufälligen Stelle und in einer zufälligen Farbe schreibt. 2D zufälliger Spaziergang Schreiben Sie ein Programm RandomWalk. java, um einen 2D zufälligen Spaziergang zu simulieren und die Ergebnisse zu beleben. Starten Sie in der Mitte eines 2N-by-2N-Rasters. Der aktuelle Standort wird in blau den Weg in weiß angezeigt. Drehtisch Sie sitzen an einem drehbaren quadratischen Tisch (wie eine faule Susan), und es sind vier Münzen in den vier Ecken des Tisches platziert. Ihr Ziel ist es, die Münzen zu drehen, so dass sie entweder alle Köpfe oder alle Schwänze sind, an welcher Stelle eine Glocke läutet, um Sie zu benachrichtigen, dass Sie fertig sind. Sie können zwei beliebige auswählen, ihre Orientierung bestimmen und (optional) entweder oder beide beenden. Um die Dinge anspruchsvoll zu machen, bist du mit verbundenen Augen, und der Tisch wird nach jedem Mal, wenn du zwei Münzen auswählst, gesponnen. Schreiben Sie ein Programm RotatingTable. java, das die Münzen in zufällige Orientierungen initialisiert. Dann fordert es den Benutzer auf, zwei Positionen (1-4) auszuwählen und identifiziert die Ausrichtung jeder Münze. Als nächstes kann der Benutzer angeben, welche, wenn eine der beiden Münzen zu kippen. Der Prozess wiederholt sich, bis der Benutzer das Puzzle löst. Drehender Tischlöser Schreiben Sie ein anderes Programm RotatingTableSolver. java, um das rotierende Tischpuzzle zu lösen. Eine effektive Strategie ist, zwei Münzen zufällig zu wählen und sie zu den Köpfen zu kippen. Allerdings, wenn Sie wirklich Pech bekommen, könnte dies eine beliebige Anzahl von Schritten zu nehmen. Ziel: eine Strategie entwickeln, die das Rätsel immer in höchstens 5 Schritten löst. Verhexen. Hex ist ein Zwei-Spieler-Brettspiel, das von John Nash als Student an der Princeton University popularisiert wird und später von Parker Brothers kommerzialisiert wird. Es wird auf einem sechseckigen Gitter in Form eines 11-mal-11-Diamanten gespielt. Schreiben Sie ein Programm Hex. java, das das Brett zeichnet. Projektilbewegung mit Drag. Schreiben Sie ein Programm BallisticMotion. java, das die Trajektorie eines Balles, der mit Geschwindigkeit v in einem Winkel Theta erschossen wird, Konto für Gravitations - und Schleppkräfte. Nehmen wir an, dass die Schleppkraft proportional zum Quadrat der Geschwindigkeit ist. Unter Verwendung von Newton-Gleichungen von Bewegungen und der Euler-Cromer-Methode aktualisieren Sie die Position, die Geschwindigkeit und die Beschleunigung gemäß den folgenden Gleichungen: Verwenden Sie G 9.8, C 0,002 und stellen Sie die Anfangsgeschwindigkeit auf 180 und den Winkel auf 60 Grad ein. Herz. Schreiben Sie ein Programm Heart. java, um ein rosa Herz zu zeichnen: Zeichnen Sie einen Diamanten, dann ziehen Sie zwei Kreise nach oben links und oben rechts. Platzwechsel. Schreiben Sie ein Programm, das ein Quadrat zeichnet und seine Farbe jede Sekunde ändert. Einfache harmonische Bewegung. Wiederholen Sie die vorherige Übung, aber beleben Sie die Lissajous Muster wie in diesem Applet. Ex: A B w x w y 1, aber zu jedem Zeitpunkt t zeichnen Sie 100 (oder so) Punkte mit phi x von 0 bis 720 Grad und phi x im Bereich von 0 bis 1080 Grad. Bresenhams zeichnen Algorithmus. Um ein Liniensegment von (x1, y1) bis (x2, y2) auf einem Monitor zu markieren, z. B. 1024-mal-1024, müssen Sie eine diskrete Annäherung an die durchgezogene Linie vornehmen und genau bestimmen, welche Pixel eingeschaltet werden sollen. Bresenhams Linie Zeichnung Algorithmus ist eine clevere Lösung, die funktioniert, wenn die Steigung zwischen 0 und 1 ist und x1 Ändern Bresenhams Algorithmus, um beliebige Liniensegmente zu behandeln. Millers Wahnsinn. Schreiben Sie ein Programm Madness. java, um die parametrische Gleichung zu zeichnen: wo der Parameter t im Bogenmaß ist. Sie sollten das folgende komplexe Bild erhalten. Experimentieren Sie, indem Sie die Parameter ändern und Originalbilder erzeugen. Fays Schmetterling. Schreiben Sie ein Programm Butterfly. java, um die polare Gleichung zu zeichnen: wo der Parameter t im Bogenmaß ist. Sie sollten ein Bild wie die folgende Schmetterling-ähnliche Figur bekommen. Experimentieren Sie, indem Sie die Parameter ändern und Originalbilder erzeugen. Studentendatenbank Die Datei students. txt enthält eine Liste der Schüler, die in einer einführenden Informatik-Klasse bei Princeton eingeschrieben sind. Die erste Zeile enthält eine Ganzzahl N, die die Anzahl der Schüler in der Datenbank angibt. Jede der nächsten N Zeilen besteht aus vier Informationen, die durch Leerzeichen getrennt sind: Vorname, Nachname, E-Mail-Adresse und Abschnittsnummer. Das Programm Students. java liest in der Integer N und dann N Zeilen von Daten der Standard-Eingabe, speichert die Daten in vier parallelen Arrays (ein Integer-Array für die Section-Nummer und String-Arrays für die anderen Felder). Dann druckt das Programm eine Liste der Schüler in Abschnitt 4 und 5. Shuffling. In der 7. Oktober 2003 Kalifornien Staat Abfluss Wahl für Gouverneur, gab es 135 offizielle Kandidaten. Um das natürliche Vorurteil gegen Kandidaten zu vermeiden, deren Namen am Ende des Alphabets (Jon W. Zellhoefer) erscheinen, suchten Kalifornien-Wahlbeamte die Kandidaten in zufälliger Reihenfolge zu bestellen. Schreiben Sie ein Programmprogramm Shuffle. java, das ein Befehlszeilenargument N einnimmt, liest in N Strings von der Standardeingabe und druckt sie in shuffled Reihenfolge zurück. (California decided to randomize the alphabet instead of shuffling the candidates. Using this strategy, not all N possible outcomes are equally likely or even possible For example, two candidates with very similar last names will always end up next to each other.) Reverse. Write a program Reverse. java that reads in an arbitrary number of real values from standard input and prints them in reverse order. Time series analysis. This problem investigates two methods for forecasting in time series analysis. Moving average or exponential smoothing. Polar plots. Create any of these polar plots. Java games. Use StdDraw. java to implement one of the games at javaunlimited. Consider the following program. Suppose the file input. txt contains the following integers: What is the contents of the array a after running the following command High-low. Shuffle a deck of cards, and deal one to the player. Prompt the player to guess whether the next card is higher or lower than the current card. Repeat until player guesses it wrong. Game show. used this. Elastic collisions. Write a program CollidingBalls. java that takes a command-line argument n and plots the trajectories of n bouncing balls that bounce of the walls and each other according to the laws of elastic collisions. Assume all the balls have the same mass. Elastic collisions with obstacles. Each ball should have its own mass. Put a large ball in the center with zero initial velocity. Brownian motion. Statistical outliers. Modify Average. java to print out all the values that are larger than 1.5 standard deviations from the mean. You will need an array to store the values. Optical illusions. Create a Kofka ring or one of the other optical illusions collected by Edward Adelson. Computer animation. In 1995 James Gosling presented a demonstration of Java to Sun executives, illustrating its potential to deliver dynamic and interactive Web content. At the time, web pages were fixed and non-interactive. To demonstrate what the Web could be, Gosling presented applets to rotate 3D molecules, visualize sorting routines, and Duke cart-wheeling across the screen. Java was officially introduced in May 1995 and widely adopted in the technology sector. The Internet would never be the same. Program Duke. java reads in the 17 images T1.gif through T17.gif and produces the animation. To execute on your computer, download the 17 GIF files and put in the same directory as Duke. java . (Alternatively, download and unzip the file duke. zip or duke. jar to extract all 17 GIFs.) Cart-wheeling Duke. Modify Duke. java so that it cartwheels 5 times across the screen, from right to left, wrapping around when it hits the window boundary. Repeat this cart-wheeling cycle 100 times. Hinweis. after displaying a sequence of 17 frames, move 57 pixels to the left and repeat. Name your program MoreDuke. java. Tac (cat backwards). Write a program Tac. java that reads lines of text from standard input and prints the lines out in reverse order. Game. Implement the game dodge using StdDraw . move a blue disc within the unit square to touch a randomly placed green disc, while avoiding the moving red discs. After each touch, add a new moving red disc. Simple harmonic motion. Create an animation like the one below from Wikipedia of simple harmonic motion. Yin yang. Draw a yin yang using StdDraw. arc() . Twenty questions. Write a program QuestionsTwenty. java that plays 20 questions from the opposite point of view: the user thinks of a number between 1 and a million and the computer makes the guesses. Use binary search to ensure that the computer needs at most 20 guesses. Write a program DeleteX. java that reads in text from standard input and deletes all occurrences of the letter X. To filter a file and remove all Xs, run your program with the following command: Write a program ThreeLargest. java that reads integers from standard input and prints out the three largest inputs. Write a program Pnorm. java that takes a command-line argument p, reads in real numbers from standard input, and prints out their p-norm . The p-norm norm of a vector (x 1 . x N ) is defined to be the pth root of (x 1 p x 2 p . x N p ). Consider the following Java program. Suppose that the file input. txt contains the integers 1 and 1. What does the following command do Modify Add. java so that it re-asks the user to enter two positive integers if the user types in a non-positive integer. Modify TwentyQuestions. java so that it re-asks the user to enter a response if the user types in something other than true or false . Hint: add a do-while loop within the main loop. Nonagram. Write a program to plot a nonagram. Star polygons. Write a program StarPolygon. java that takes two command line inputs p and q, and plots the - star polygon. Complete graph. Write a program to plot that takes an integer N, plots an N-gon, where each vertex lies on a circle of radius 256. Then draw a gray line connecting each pair of vertices. Necker cube. Write a program NeckerCube. java to plot a Necker cube. What happens if you move the StdDraw. clear(Color. BLACK) command to before the beginning of the while loop in BouncingBall. java. Answer . try it and observe a nice woven 3d pattern with the given starting velocity and position. What happens if you change the parameter of StdDraw. show() to 0 or 1000 in BouncingBall. java. Write a program to plot a circular ring of width 10 like the one below using two calls to StdDraw. filledCircle() . Write a program to plot a circular ring of width 10 like the one below using a nested for loop and many calls to StdDraw. point() . Write a program to plot the Olympic rings. Write a program BouncingBallDeluxe. java that embellishes BouncingBall. java by playing a sound effect upon collision with the wall using StdAudio and the sound file pipebang. wav. Last modified on February 20, 2017. Copyright copy 2000ndash2016 Robert Sedgewick and Kevin Wayne. All rights reserved. Slightly Skeptical View on Sorting Algorithms This is a very special page: here students can find several references and actual implementation for Bubblesort :-). Actually b ubblesort is a rather weak sorting algorithm for arrays that for some strange reason dominates introductory courses. It39s not that bad on lists and on already sorted arrays (or quotalmost sortedquot arrays), but that39s another story. An important point is that it is very often implemented incorrectly. Note: When writing or debugging soft algorithms, UNIX sort can often be used to check results for correctness (you can automate it to check several tricky cases, not just one sample). Diff with Unix sort results will instantly tell you if you algorithms works correctly or not if all keys are distinct. If there are multiple identical keys your mileage may vary -). Sorting algorithms can be stable (which preserve the initial sequence of records with identical keys and non-stable -- which, as you can guess, do not. Among simple sorting algorithms, the insertion sort seems to be better for small sets. It is stable and works perfectly on quotalmost sortedquot arrays. The latter case is probably the most important class of input data for sorting algorithms. Selection sort . while not bad, does not takes advantage of the preexisting sorting order and is not stable . At the same time it moves quotdissidentquot elements by larger distances then insertion sort, so the total number of moves might well be less. But a move typically cost about the same as unsuccessful comparison (on modern computer with predictive execution comparison that results in a jump which cost 10 or more times then when comparison that does not change order of execution (typically successful comparison). So it is total number of comparisons plus total number of moves that counts. Despite this fact it is still make sense to judge algorithms by just the number of comparisons. And it is clear that algorithms do not use comparisons at all have significant advantages on modern computers. Again, total number of comparisons and moves is a better metric. But not all comparisons are reated equal -- what really matter are unsuccessful comparisons, not so much successful one. An Unsucessful comparison results in a jump in compiled code which forces the flush of the instruction pipeline. The second important fact is the size of the set. There is no and cant be a sorting algorithms that is equally efficient of small sets and on large sets. For small sets quotoverheadquot of the algorithms itself is an important factor so the simpler algorithm is the better it performs on small sets. Several more complex algorithms such as radixsort (which does not used comparisons), shellsort. mergesort. heapsort. and even quite fragile, but still fashionable quicksort are much faster on larger sets. Mergesort is now used by several scripting languages as internal sorting algorithm instead of Quicksort. A least significant digit (LSD) radix sort recently has resurfaced as an alternative to other high performance comparison-based sorting algorithms for integer keys and short strings (like Heapsort and Mergesort) because it does not use comparisons and can utilize modern CPUs much better then traditional comparison based algorithms. Anyway, IMHO if an instructor uses bubblesort as an example you should be slightly vary -). The same is true if Quicksort is over-emphasized in the course as all singing-all dancing solution for sorting large sets. But the most dangerous case is when the instructor emphasizes object oriented programming while describing sorting. That applies to book authors too. It39s better to get a second book in such case, as typically those guys try to obscure the subject making it more complex (and less interesting) than it should be. Of course, as a student you have no choice and need to pass the exam, but be very wary of this trap of mixing apples and oranges. You might fail to understand the course material just because the instructor is too preoccupied with OO machinery instead of algorithms. So while you may feel that you are incapable to master the subject, in reality that simply means that the instructor is an overcomplexity junky, nothing more nothing less -). In any case OO obscures the elegance of sorting algorithms to such an extent that most students hate the subject for the rest of their life. If this is the case, that only means that you are normal. Classic treatise on sorting algorithms remains Volume 3 of TAoCP by Donald Knuth. The part of the book in which sorting algorithms are explained is very short (the volume also covers searching and several other subjects). Just the first 180 pages. You can buy the first edition for 3-5 dollars (and they are still as good as later editions for teaching purposes as Knuth did s good job in the first edition and never improved on it in later editions -- changes are mostly small corrections and typographic niceties please not the flowcharts in the book are a horrible mess -- shame on Knuth) Unfortunately the third volume was written when Knuth was already pretty much exhausted by publishing the first two volumes and that shows. The third volume also was based not on Knuth own research but on lecture notes of Professor Robert W. Floyd. one of the few winners of ACM Turing prise. the top 50 scientists and technologists of the USA early computer science explosion. Also at the moment of writing the field still quickly developed and this fact is reflected in the unevenness of the book content, where some algorithms are well covered but other not so well. Now it can be viewed as the most outdated volume out of three, despite the fact that it was published last. Nevertheless it remains classic because Knuth is Knuth, and his touch on the subject can39t be replicated easily. As any classic, it is quite difficult to read (examples are in MIX assembler and growing on ancient IBM 650 Knuth missed the value of System360 instruction set). Still like classic should, it produces insights that you never get reading regular textbooks. The most valuable are probably not the content but exercises. Most of the content of volume 3 can now be found in other books, although in somewhat emasculated fashion. Again I would like to warn you that the main disaster in courses quotData structures and algorithmsquot happens when they try to mix applies with oranges, poisoning sorting algorithms by injecting into the course pretty much unrelated subject -- OO. And it is students in this case who suffer, not the instructor -) Complexity of the algorithms is just one way to classify sorting algorithms. Es gibt viele andere. One important classification is based on the internal structure of the algorithm: Swap-based sorting algorithms begin conceptually with the entire list, and exchange particular pairs of elements (adjacent elements like in bubblesort or elements with a certain step like in Shell sort) moving toward a more sorted list. Merge-based sorting algorithms creates initial quotnaturallyquot or quotunnaturallyquot sorted sequences, and then add either element by element to it preserving sorting order (insertion sort) or merge two already sorted sequences until there is a single sorting segment, encompassing all the data. Tree-based sorting algorithms store the data, at least conceptually, in a binary tree there are two different approaches, one based on heaps, and the other based on search trees. Sorting by distribution algorithms (See Knuth Vol 3, 5.2.5. Sorting by distribution. P.168) use additional key-value information . implicit in storing digits and strings in computer. The classic example of this type of algorithms is so called radix sort. Radix Sort processes array elements one digit at a time, starting either from the most significant digit (MSD) or the least significant digit (LSD). MSD radix sorts use lexicographic order, which is especially suitable for sorting strings, such as words, or fixed-length integer representations. A least significant digit (LSD) radix sort is suitable only for short keys (for example integers or IP addresses) and when all keys have the same length (or can padded to the same length) and is a fast stable sorting algorithm. It is suitable, for example for sorting log records by IP address. See also Bucket sort and postman sort We can also classify sorting algorithms by several other criteria such as: Computational complexity (worst, average and best number of comparisons for several typical test cases, see below) in terms of the size of the list ( n ). Typically, good average number of comparisons is O ( n log n ) and bad is O( n 2 ). Please note that O matters. Even if both algorithms belong to O ( n log n ) class, algorithm for which O1 is 100 times faster then algorithm for which O100. Another problem with O notation is that this asymptotic analysis does not tell about algorithms behavior on small lists, or worst case behavior. This is actually one of the drawback of Knuth book in which he was carried too much by the attempt to establish theoretical bounds on algorithms. Worst case behavior is probably more important then average. For example quotplain-vanillaquot quicksort requires O( n 2 ) comparisons in case of already sorted or almost sorted array: a very important in practice case as in many case sorting is used as quot incompetent people merge quot instead of merging two sets the second set concatenated to the sorted set and then the whole array is resorted. If you get statistic of usage of Unix sort in some large datacenter you will be see that a lot of sorting used for processing huge log files and then resorting them for additional key. For example the pipeline can be applied to 100M or larger file and this script can be processed daily. Sort algorithms which only use generic key comparison operation always need at least O( n log n ) comparisons on average while sort algorithms which exploit the structure of the key space cannot sort faster than O(n log k) where k is the size of the keyspace. So if key space is much less then N (a lot of records with identical keys), no comparison algorithms is completive with radix type sorting. Please note that the number of comparison is just convenient theoretical metric. In reality both moves and comparisons matter, and failed comparisons matter more then successful also on short keys the cost of move is comparable to the cost of successful comparison (even if pointers are used). Stability: stable sorting algorithms maintain the relative order of records with equal keys. If all keys are different then this distinction does not make any sense. But if there are equal keys, then a sorting algorithm is stable if whenever there are two records R and S with the same key and with R appearing before S in the original list, R will appear before S in the sorted list. Among simple algorithms bubble sort and insertion sort are stable. Among efficient complex algorithms only Mergesort is stable. A least significant digit (LSD) radix sort is suitable only for short keys (for example integers or IP addresses) and when all keys have the same length (or can padded to the same length) and is a fast stable sorting algorithm. Staqbility is a valuable property of sorting algorithms. Memory usage (and use of other computer resources). One large class of algorithms are quotin-place sorting. They are generally slower than algorithms that use additional memory . additional memory can be used for mapping of keyspace. Most fast stable algorithms use additional memory. With the current 16GB typical memory size on laptops and 64GB typical memory size on the servers as well as virtual memory used in all major OSes, the old emphasis on algorithms that does not require additional memory should probably be abandoned. Speedup that can be achieved by using of a small amount of additional memory is considerable and it is stupid to ignore it. Moreover even for classic in-place algorithms you can always use pointers to speed up moving records. for long records this additional space proportional to N actually speed up moved dramatically and just due to this such an implementation will outcompete other algorithms. In other words when sorting records not to use pointers in modern machines in any case when the record of the sorting array is larger then 64 bit is not a good strategy. In real life sorting records usually are size several times bigger then the size of a pointers (4 bytes in 32 bit CPUs, 8 bytes on 64 bit). That means that, essentially, study of sorting algorithms on just integer arrays is a much more realistic abstraction, then it appear from the first site. In modern computer multi-level memory is used. Cache-aware versions of the sort algorithms, whose operations have been specifically chosen to minimize the movement of pages in and out cache, can be dramatically quicker. One example is the tiled merge sort algorithm which stops partitioning sub arrays when subarrays of size S are reached, where S is the number of data items fitting into a single page in memory. Each of these subarrays is sorted with an in-place sorting algorithm, to discourage memory swaps, and normal merge sort is then completed in the standard recursive fashion. This algorithm has demonstrated better performance on machines that benefit from cache optimization. (LaMarca amp Ladner 1997 ) Modern CPUs designs try to minimize wait states of CPU that are inevitable due to the fact that it is connected to much slower (often 3 or more times) memory using a variety of techniques such as CPU caches. instruction pipelines. instruction prefetch. branch prediction. For example, the number of instruction pipeline (see also Classic RISC pipeline - Wikipedia ) flushes (misses) on typical data greatly influence the speed of algorithm execution. Modern CPU typically use branch prediction (for example The Intel Core i7 has two branch target buffers and possibly two or more branch predictors). If branch guessed incorrectly penalty is significant and proportional to the number of stages in the pipeline. So one possible optimization of code strategy for modern CPUs is reordering branches, so that higher probability code was located after the branch instruction. This is a difficult optimization that requires thorously instrumentation of algorithms and its profiling. gathering set of statistics about branching behaviors based on relevant data samples as well as some compiler pragma to implement it. In any case this is important factor for modern CPUs which have 7, 10 and even 20 stages pipelines (like in the Intel Pentium 4 ) and were cost of a pipeline miss can cost as much as three or fours instructions executed sequentially. The difference between worst case and average behavior . For example, quicksort is efficient only on the average, and its worst case is n 2. while heapsort has an interesting property that the worst case is not much different from the an average case. Behaviors on practically important data sets such as completely sorted (you will be surprised how many sorting operations are performed on already sorted data, inversely sorted and 39almost sorted39 (1 to K permutations, where K is less then N10). The latter is often used as a perverted way of inserting one or two records into a large data set: instead of merging them they are added to the bottom and the whole dataset is sorted. Those has tremendous practical implications which are often not addressed or addressed incorrectly in textbooks that devote some pages to sorting. Among non-stable algorithms heapsort and Shellsort are probably the most underappreciated and quicksort is one of the most overhyped. Please note the quicksort is a fragile algorithm that is not that good in using predictive execution of instructions in pipeline (typical feature of modern CPUs). There are practically valuable sequences (quotnear sortedquot data sets) in which for example shellsort is twice faster then quicksort (see examples below). It is fragile because the choice of pivot is equal to guessing an important property of the data to be sorted (and if it went wrong the performance can be close to quadratic). There is also some experimental evidence that on very large sets Quicksort runs into quotsuboptimal partitioningquot on a regular basis, so it becomes a feature, not a bug. It does not work well on already sorted or quotalmost sortedquot (with a couple or permutations) data as well as data sorted in a reverse order. It does not work well on data that contain a lot of identical keys. Those are important cases that are frequent in real world usage of sorting. Again I would like to stress that one will be surprised to find what percentage of sorting is performed on already sorted datasets or datasets with less then 10 of permutations. For those (and not only for those -) reasons you need to be skeptical about quot quicksort lobbyquot with Robert Sedgewick (at least in the past) as the main cheerleader. Quicksort is a really elegant algorithm invented by Hoare in Moscow in 1961, but in real life other qualities then elegance and speed of random data are more valuable -). On important practical case of quotsemi-sortedquot and quotalmost reverse sortedquot data quicksort is far from being optimal and often demonstrates dismal performance. You need to do some experiments to see how horrible quicksort can be in case of already sorted data (simple variants exhibit quadratic behavior, the fact that is not mentioned in many textbooks on the subject) and how good shellsort is -). And on typical corporate data sets including log records heapsort usually beats quicksort because performance of quicksort too much depends of the choice of pivot and series of bad choices increase time considerably. Each time the pivot element is close to minimum (or maximum) the performance of this stage goes into the drain and on large sets such degenerative cases are not only common, they can happen in series (I suspect that on large data setsquick sort quotself-createdquot such cases -- in other words quicksort poisons its data during partitions making bad choices of pivot progressively more probable). Here are results from one contrarian article written by Paul Hsieh in 2004 Athlon XP 1.620Ghz Data is time in seconds taken to sort 10000 lists of varying size of about 3000 integers each. Download test here Please note that total time while important does not tell you the whole story. Actually it reveals that using Intel compiler Heapsort can beat Quicksort even quoton averagequot -- not a small feat. You need also know the standard deviation. Actually one need to read volume 3 of Knuth to appreciate the beauty and complexity of some advanced sorting algorithms. Please note that sorting algorithms published in textbooks are more often then not implemented with errors. Even insertion sort presents a serious challenge to many book authors -). Sometimes the author does not know the programming language heshe uses well, sometimes details of the algorithm are implemented incorrectly. And it is not that easy to debug them. In this sense Knuth remains quotthe referencequot, one of the few books where the author took a great effort to debug each and every algorithm he presented. Please take any predictions about relative efficiency of algorithms with the grain of salt unless they are provided for at least a dozen typical sets of data as described below. Shallow authors usually limit themselves to random sets, which are of little practical importance. So please do not spend much time browsing web references below. They are not as good as Knuth39s volume. It is clear the you never will use sorting algorithms in worst case O( n 2 ) in real time avionics computers -). In order to judge suitability of a sorting algorithms to a particular application you need to see: Are the data that application needs to sort tend to have some preexisting order. What are properties of keyspace Do you need a stable sort Can you use some quotextraquot memory or need quotin-placequot soft. (with the current computer memory sizes you usually can afford some additional memory so quotin-placequot algorithms no longer have any advantages). Generally the more we know about the properties of data to be sorted, the faster we can sort them. As we already mentioned the size of key space is one of the most important dimensions (sort algorithms that use the size of key space can sort any sequence for time O(n log k) ). For example if we are sorting subset of a card deck we can take into account that there are only 52 keys in any input sequence and select an algorithms that uses limited keyspace for dramatic speeding of the sorting. In this case using generic sorting algorithm is just a waist. Moreover, the relative speed of the algorithms depends on the size of the data set: one algorithm can be faster then the other for sorting less then, say, 64 or 128 items and slower on larger sequences. Simpler algorithms with minimal housekeeping tend to perform better on small sets even if the are O( n 2 ) type of algorithms. Especially algorithms that have less number of jump statement in compiled version of code. For example insertion sort is competitive with more complex algorithms up to N25 or so. There is not quotbest sorting algorithmquot for all data. Various algorithms have their own strength and weaknesses. For example some quotsensequot already sorted or quotalmost sortedquot data sequences and perform faster on such sets. In this sense Knuth math analysis is insufficient althouth quotworst timequot estimates are useful. As for input data it is useful to distinguish between the following broad categories that all should be used in testing (random number sorting is a very artificial test and as such the estimate it provides does not have much practical value, unless we know that other cases behave similarly or better): Completely randomly reshuffled array (this is the only test that naive people use in evaluating sorting algorithms). Already sorted array (you need to see how horrible Quicksort is on this case and how good shellsort is -). This is actually a pretty important case as often sorting is actually resorting of previously sorted data done after minimal modifications of the data set. There are three imortant case of already sorted array Array of distinct elements sorted in quotrightquot direction for which no any reordering is required (triangular array). Already sorted array consisting of small number of identical elements (stairs). The worst case is rectangular array in when single element is present (all values are identical). Already sorted in reverse order array (many algorithms, such as insertion sort work slow on such an array) Array that consisted of merged already sorted arrays(Chainsaw array). Arrays can be sorted in right direction in opposite direction of have arrays both sorted in right and opposite direction (one case is quotsymmetrical chainsawquot). Array consisting of small number of identical elements (sometimes called or quotfew uniquequot case). If number of distinct elements is large this is the case similar to chainsaw but without advantage of preordering. So it can be generated by quotinflictingquot certain number of permutations on chainsaw array. Worst case is when there is just two values of elements in the array (binary array). Quicksort is horrible on such data. Many other algorithms work slow on such an array. Already sorted in right direction array with N permutations (with N from 0.1 to 10 of the size). Insrtion soft does well on such arrays. Shellsort also is quick. Quick sort do not adapt well to nearly sorted data. Already sorted array in reverse order array with N permutations Large data sets with normal distribution of keys. Pseudorandom data (daily values of SampP500 or other index for a decade or two might be a good test set here they are available from Yahoo ) Behavior on quotalmost sortedquot data and worst case behavior are a very important characteristics of sorting algorithms. For example, in sorting n objects, merge sort has an average and worst-case performance of O ( n log n ). If the input is already sorted, its complexity falls to O ( n ). Specifically, n-1 comparisons and zero moves are performed, which is the same as for simply running through the input, checking if it is pre-sorted. In Perl 5.8, merge sort is its default sorting algorithm (it was quicksort in previous versions of Perl). Python uses timsort. a hybrid of merge sort and insertion sort, which will become the standard sort algorithm for Java SE 7. Calculation of the number of comparisons and number of data moves can be done in any language. C and other compiled languages provide an opportunity to see the effect of computer instruction set and CPU speed on the sorting performance. Usually the test program is written as a subroutine that is called, say, 1000 times. Then data entry time (running just data coping or data generating part the same number of times without any sorting) is subtracted from the first. Such a method can provide more or less accurate estimate of actual algorithms run time on a particular data set and particular CPU architecture. Modern CPUs that have a lot of general purpose registers tend to perform better on sorting: sorting algorithms tend to belong to the class of algorithms with tight inner loop and speed of this inner loop has disproportionate effect on the total run time. If most scalar variables used in this inner look can be kept in registers times improves considerably. Artificial computers like Knuth MIXX can be used too. In this case the time is calculated based on the time table of performing of each instruction (instruction cost metric). While choosing the language is somewhat a religious issue, there are good and bad language for sorting algorithms implementations. See Language Design and Programming Quotes for enlightened discussion of this touchy subject -) BTW you can use Perl or other interpreted scripting language in a similar way as assembler of artificial computer. I actually prefer Perl as a tool of exploring sorting as this is an interpreted language (you do not need to compile anything) with a very good debugger and powerful control structures. And availability of powerful control structures is one thing that matter in implementation of sorting algorithms. Life is more complex then proponents of structured programming are were trying us to convince. Please note that a lot of examples in the books are implemented with errors. That39s especially true for Java books and Java demo implementations. Use Knuth book for reference. An alternative taxonomy (to that of Knuth and others) of sorting algorithms is proposed. It emerges naturally out of a top-down approach to the derivation of sorting algorithms. Work done in automatic program synthesis has produced interesting results about sorting algorithms that suggest this approach. In particular, all sorts are divided into two categories: hardspliteasyjoin and easysplithardjoin. Quicksort and merge sort, respectively, are the canonical examples in these categories. Insertion sort and selection sort are seen to be instances of merge sort and quicksort, respectively, and sinking sort and bubble sort are in-place versions of insertion sort and selection sort. Such an organization introduces new insights into the connections and symmetries among sorting algorithms, and is based on a higher level, more abstract, and conceptually simple basis. It is proposed as an alternative way of understanding, describing, and teaching sorting algorithms. Data Structures and Algorithms with Object-Oriented Design Patterns in C online book by Bruno R. Preiss B. A.Sc. M. A.Sc. Ph. D. P. Eng. Associate Professor Department of Electrical and Computer Engineering University of Waterloo, Waterloo, Canada sortchk is a simple test suite I wrote in order to measure the costs (in terms of needed comparisons and data moves, not in terms of time consumed by the algorithm, as this is too dependend on things like type of computer, programming language or operating system) of different sorting algorithms. The software is meant to be easy extensible and easy to use. It was developed on NetBSD. but it will also compile and run well on other systems, such as FreeBSD, OpenBSD, Darwin, AIX and Linux. With little work, it should also be able to run on foreign platforms such as Microsoft Windows or MacOS 9. Sorting Algorithms Implementations of sorting algorithms. Sorting Algorithms Demo Demonstrated with 15 java applets. Cool The Improved Sorting Algorithm Demo Lots of sorting (18) algorithms demos. Heap sort visualization A short primer on the heap sort algorithm a user39s guide to learn the applet39s interface and how it works. Finally, check out the visualization applet itself to dissect this truly elegent sorting algorithm. Technical documentation is also available for anyone wanting to see how this applet was designed and implemented in the Java language. From there, the source code is explained. Merge Sort Algorithm Simulation With good explanation. Sandeep Mitra39s Java Sorting Animation Page Nine classic algorithms with explanation. MergeSort demo with comparison bounds With merge sort description. The Sorting Algorithm Demo Sequential and parallel - includes also time analysis. Sorting Algorithms Nine algorithms demonstrated. Sort Animator Bubble, Insertion, Selection, Quicksort, Shell, Merge sort demonstrated. The Sorting Algorithm Demo 6 classics algorithms (Bubble Bi, Quick, Insert, Heap and Shell). Analysis of Sorting Algorithm Merge Sort, Insertion Sort, and a combination MergeInsertion Sort compared. Don Stone39s Program Visualization Page Different sorts visualized on your PC (Old MsDos view) Sorting Algorithms Bookmark for sorting algorithms demos. Welcome to Sorting Animation Insertion, Shell, Heap, Radix and Quicksort explained in clear way, by Yin-So Chen. Animation of Sort Algorithms Java - five algorithms. Illustration of sorting algorithms BubbleSort, Bidirectional BubbleSort, QuickSort, SelectionSort, Insertionsort and ShellSort Sorting Demo is a powerful tool for demonstrating how sorting algorithms work. It was designed to alleviate some of the difficulty instructors often have in conveying these concepts to students due to lack of blackboard space and having to constantly erase. This program started out as a quicksort demonstration applet, and after proposing the idea to Seton Hall39s math and computer science department, I was given permission to expand the idea to encompass many of the sorts commonly taught in a data structuresalgorithms class. There are currently 9 algorithms featured, all of which allow you to either type in your own array or make the computer generate a random array of a milestone size. Although graphics limit the input array to a length of 25 elements, there is the option to run the algorithm without graphics in order to get an understanding of its running time in comparison with the other sorts. We all know that Quicksort is one of the fastest algorithms for sorting. It39s not often, however, that we get a chance to see exactly how fast Quicksort really is. The following applets chart the progress of several common sorting algorthms while sorting an array of data using constant space algorithms. (This is inspired by the algorithm animation work at Brown University and the video Sorting out Sorting from the University of Toronto (circa 1970).) This applet lets you observe the dynamic operation of several basic sort algorithms. The implementations, explanations and display technique are all taken from Algorithms in C, third Edition, Sedgewick, 1998. Generate a data set by clicking one of the data set buttons. This generates a data set with the appropriate characteristics. Each data set is an array of 512 values in the range 0..511. Data sets have no duplicate entries except the Gaussian distribution. Run one or more sort algorithms on the data set to see how the algorithm works. Each execution of a sort runs on the same data set until you generate a new one. Animator for selection sort Provided by - Peter Brummund through the Hope College Summer Research Program. Algorithms covered: Bubble Sort -- incorrect implementation Insertion Sort Merge Sort Quick Sort Selection Sort Shell Sort Softpanorama hot topic of the month Softpanorama Recommended Sorting - Wikipedia, the free encyclopedia This is a collection of algorithms for sorting and searching. Descriptions are brief and intuitive, with just enough theory thrown in to make you nervous. I assume you know a high-level language, such as C, and that you are familiar with programming concepts including arrays and pointers. The first section introduces basic data structures and notation. The next section presents several sorting algorithms. This is followed by a section on dictionaries . structures that allow efficient insert . search . and delete operations. The last section describes algorithms that sort data and implement dictionaries for very large files. Source code for each algorithm, in ANSI C, is included. Most algorithms have also been coded in Visual Basic. If you are programming in Visual Basic, I recommend you read Visual Basic Collections and Hash Tables. for an explanation of hashing and node representation. If you are interested in translating this document to another language, please send me email. Special thanks go to Pavel Dubner, whose numerous suggestions were much appreciated. The following files may be downloaded: shetot-ch3.htm shetot-ch4.htm Sorting Algorithms -- some explanation of simple sorting algorithms Sorting Algorithms - Skolnick -- very good explanation of insertion sort and selection sort. Insertion sort quotinsertsquot each element of the array into a sorted sub-array of increasing size. Initially, the subarray is of size 0. It depends on the insert function shown below to insert an element somewhere into a sorted array, shifting everything to the right of that element over one space. Sorting Algorithms Page -- several C programs for simple sorting argorithms (Insertion, Bubblesort, Selection sort) and several advanced (Quicksort, Mergesort, Shellsort, Heapsort) Definitions of Algorithms Data Structures and Problems Algorithms A Help Site -- a pretty raw Mustafa39s Modified Sorting Algorithms Outline Chapter 8 the source code for the chapter on Sorting from Algorithms, Data Structures, and Problem Solving with C, by Mark Allen Weiss. Sorting Algorithms -- tutorial with animations Sorting Algorithms The Complete Collection of Algorithm Animations Some sorting algorithms -- Pascal Sorting Algorithms P. M. McIlroy, K. Bostic and M. D. McIlroy, Engineering radix sort . Computing Systems 6 (1993) 5-27 gzipped PostScript (preprint) M. D. McIlroy, A killer adversary for quicksort . Software--Practice and Experience 29 (1999) 341-344, gzipped PostScript or pdfCategory:Programming Tasks Programming tasks are problems that may be solved through programming. When such a task is defined, Rosetta Code users are encouraged to solve them using as many different languages as they know. The end goal is to demonstrate how the same task is accomplished in different languages. These are the Programming Tasks that have been defined and solved. Feel free to add solutions in languages not already included. The Category:Simple is a small subset with only really simple tasks, like Hello World, and demonstrations of basic language-features. The Category:Draft Programming Tasks is a list of tasks, some of which are just awaiting more implementations before they can be promoted to tasks. Others may well have problems, (check their discussion and history pages). Read the guidelines on creating new tasks. If you need help, check the discussion for this page. Pages in category Programming Tasks The following 834 pages are in this category, out of 834 total.

No comments:

Post a Comment