Monday 17 July 2017

Knuth Moving Average


1.5 Input dan Output Pada bagian ini kita memperluas himpunan abstraksi sederhana (input baris perintah dan keluaran standar) yang telah kita gunakan sebagai antarmuka antara program Java dan dunia luar untuk memasukkan input standar. Gambar standar Dan audio standar. Masukan standar memudahkan kita menulis program yang memproses jumlah input sewenang-wenang dan untuk berinteraksi dengan standar program kita sehingga memungkinkan kita untuk bekerja dengan grafis dan audio standar menambahkan suara. Tampilan mata burung Sebuah program Java mengambil nilai input dari command line dan mencetak string karakter sebagai output. Secara default, argumen command-line dan output standar dikaitkan dengan aplikasi yang mengambil perintah, yang kita sebut sebagai jendela terminal. Berikut adalah beberapa petunjuk untuk menggunakan command line di sistem anda. Mac middot Windows middot Linux Command-line arguments. Semua kelas kita memiliki metode main () yang mengambil array String sebagai argumen. Array itu adalah urutan argumen command-line yang kita ketikkan. Jika kita ingin argumen menjadi angka, kita harus menggunakan metode seperti Integer. parseInt () untuk mengubahnya dari String menjadi tipe yang sesuai. Keluaran standar Untuk mencetak nilai output dalam program kami, kami telah menggunakan System. out. println (). Java mengirimkan hasilnya ke aliran abstrak karakter yang dikenal sebagai output standar. Secara default, sistem operasi menghubungkan output standar ke jendela terminal. Semua output dalam program kami sejauh ini telah muncul di jendela terminal. RandomSeq. java menggunakan model ini: Dibutuhkan argumen baris perintah n dan dicetak ke keluaran standar urutan n nomor acak antara 0 dan 1. Untuk melengkapi model pemrograman kami, kami menambahkan perpustakaan berikut: Masukan standar. Baca nomor dan string dari pengguna. Gambar standar Plot grafis Audio standar Buat suara Keluaran standar Metode Javas System. out. print () dan System. out. println () menerapkan abstraksi keluaran standar dasar yang kita butuhkan. Namun demikian, untuk memperlakukan input standar dan keluaran standar dengan cara yang seragam (dan untuk memberikan beberapa perbaikan teknis), kami menggunakan metode serupa yang didefinisikan di perpustakaan StdOut: metode Javas print () dan println () adalah metode yang Anda miliki. Telah menggunakan Metode printf () memberi kita kontrol lebih besar terhadap tampilan output. Dasar-dasar pencetakan terformat. Dalam bentuknya yang paling sederhana, printf () membutuhkan dua argumen. Argumen pertama disebut format string. Ini berisi spesifikasi konversi yang menjelaskan bagaimana argumen kedua diubah menjadi string untuk output. Format string dimulai dengan dan diakhiri dengan kode konversi satu huruf. Tabel berikut merangkum kode yang paling sering digunakan: Format string. String format dapat berisi karakter selain untuk spesifikasi konversi. Spesifikasi konversi digantikan oleh nilai argumen (dikonversi ke string seperti yang ditentukan) dan semua karakter yang tersisa dilewatkan ke output. Beberapa argumen. Fungsi printf () dapat mengambil lebih dari dua argumen. Dalam kasus ini, format string akan memiliki spesifikasi konversi tambahan untuk setiap argumen tambahan. Berikut adalah dokumentasi lebih lanjut tentang sintaks string format printf. Masukan standar. Perpustakaan StdIn kami mengambil data dari aliran input standar yang berisi urutan nilai yang dipisahkan oleh spasi. Setiap nilai adalah string atau nilai dari salah satu tipe primitif Javas. Salah satu fitur utama aliran input standar adalah program Anda menghabiskan nilai saat membacanya. Setelah program Anda membaca sebuah nilai, Anda tidak dapat memback-up dan membacanya lagi. Perpustakaan didefinisikan oleh API berikut: Kami sekarang mempertimbangkan beberapa contoh secara rinci. Mengetik masukan Ketika Anda menggunakan perintah java untuk memanggil program Java dari command line, Anda benar-benar melakukan tiga hal: (1) mengeluarkan perintah untuk mulai menjalankan program Anda, (2) menentukan nilai argumen baris perintah, dan ( 3) mulai menentukan input stream standar. String karakter yang Anda ketik di jendela terminal setelah baris perintah adalah input stream standar. Sebagai contoh, AddInts. java mengambil argumen baris perintah n. Kemudian membaca n angka dari input standar dan menambahkannya, dan mencetak hasilnya ke output standar: Format input. Jika Anda mengetik abc atau 12,2 atau benar saat StdIn. readInt () mengharapkan sebuah int. Maka akan merespon dengan InputMismatchException. StdIn memperlakukan string karakter spasi berturut-turut yang identik dengan satu spasi dan memungkinkan Anda untuk membatasi nomor Anda dengan senar tersebut. Masukan pengguna interaktif TwentyQuestions. java adalah contoh sederhana dari sebuah program yang berinteraksi dengan penggunanya. Program ini menghasilkan bilangan bulat acak dan kemudian memberikan petunjuk kepada pengguna yang mencoba menebak jumlahnya. Perbedaan mendasar antara program ini dan yang lainnya yang telah kita tulis adalah bahwa pengguna memiliki kemampuan untuk mengubah aliran kontrol saat program dijalankan. Memproses arus input ukuran sewenang-wenang. Biasanya, aliran masukan terbatas: program Anda berjalan melalui arus input, menghabiskan nilai sampai arus kosong. Tapi tidak ada batasan ukuran input stream. Average. java berbunyi dalam urutan bilangan real dari input standar dan mencetak rata-ratanya. Pengalihan dan perpipaan Untuk banyak aplikasi, mengetikkan data input sebagai input stream standar dari jendela terminal tidak dapat dipertahankan karena dengan demikian membatasi program kita yang memproses tenaga dengan jumlah data yang bisa kita ketik. Demikian pula, kita sering ingin menyimpan informasi yang tercetak pada arus keluaran standar untuk digunakan nanti. Kita bisa menggunakan mekanisme sistem operasi untuk mengatasi kedua masalah tersebut. Mengalihkan output standar ke file. Dengan menambahkan perintah sederhana pada perintah yang memanggil sebuah program, kita dapat mengarahkan output standarnya ke file, baik untuk penyimpanan permanen atau untuk input ke program lain di lain waktu. Misalnya, perintah menentukan bahwa arus keluaran standar tidak dicetak di jendela terminal, namun harus ditulis ke file teks bernama data. txt. Setiap panggilan ke StdOut. print () atau StdOut. println () menambahkan teks di akhir file itu. Dalam contoh ini, hasil akhirnya adalah file yang berisi 1.000 nilai acak. Mengalihkan output standar dari sebuah file. Demikian pula, kita bisa mengarahkan input standar sehingga StdIn membaca data dari sebuah file, bukan jendela terminal. Sebagai contoh, perintah tersebut menampilkan urutan angka dari file data. txt dan menghitung nilai rata-ratanya. Secara khusus, simbol lt adalah perintah untuk menerapkan input stream standar dengan membaca dari file data. txt dan bukan dengan menunggu pengguna mengetik sesuatu ke jendela terminal. Saat program memanggil StdIn. readDouble (). Sistem operasi membaca nilai dari file. Fasilitas untuk mengarahkan input standar dari sebuah file memungkinkan kita memproses sejumlah besar data dari sumber manapun dengan program kita, hanya dibatasi oleh ukuran file yang dapat kita simpan. Menghubungkan dua program. Cara paling fleksibel untuk menerapkan abstraksi standar dan abstraksi standar adalah menentukan bahwa program tersebut dilaksanakan oleh program kita sendiri Mekanisme ini disebut perpipaan. Sebagai contoh, perintah berikut menentukan bahwa output standar untuk RandomSeq dan aliran input standar untuk Average adalah aliran yang sama. Filter. Untuk banyak tugas umum, lebih mudah untuk memikirkan masing-masing program sebagai filter yang mengubah aliran masukan standar ke arus keluaran standar dengan cara tertentu, RangeFilter. java mengambil dua argumen baris perintah dan mencetak pada keluaran standar dari angka-angka dari input standar. Yang termasuk dalam kisaran yang ditentukan. Sistem operasi Anda juga menyediakan sejumlah filter. Misalnya, filter sortir memberi garis pada input standar dalam urutan yang diurutkan: Filter lain yang berguna lebih banyak. Yang membaca data dari input standar dan menampilkannya di jendela terminal Anda satu layar pada satu waktu. Misalnya, jika Anda mengetik, Anda akan melihat angka sebanyak yang sesuai di jendela terminal Anda, namun lebih banyak lagi yang menunggu Anda menekan panel spasi sebelum menampilkan masing-masing layar berikutnya. Gambar standar Sekarang kita mengenalkan abstraksi sederhana untuk menghasilkan gambar sebagai keluaran. Kita membayangkan sebuah perangkat gambar abstrak yang mampu menggambar garis dan titik pada kanvas dua dimensi. Perangkat ini mampu menanggapi perintah yang dikeluarkan program kami dalam bentuk panggilan ke metode statis di StdDraw. Antarmuka utama terdiri dari dua macam metode: menggambar perintah yang menyebabkan perangkat melakukan tindakan (seperti menggambar garis atau menggambar sebuah titik) dan perintah kontrol yang mengatur parameter seperti ukuran pena atau skala koordinat. Perintah menggambar dasar Kami pertama-tama mempertimbangkan perintah gambar: Metode ini hampir mendokumentasikan sendiri: StdDraw. line (x0, y0, x1, y1) menarik segmen garis lurus yang menghubungkan titik (x 0 y 0) dengan titik (x 1 y 1). StdDraw. point (x, y) menggambar titik yang terpusat pada titik (x. Y). Skala koordinat default adalah satuan persegi (semua x - dan y-coordinates antara 0 dan 1). Implementasi standar menampilkan kanvas di jendela pada layar komputer Anda, dengan garis hitam dan titik pada latar belakang putih. Gambar pertama kamu HelloWorld untuk pemrograman grafis dengan StdDraw adalah menggambar segitiga dengan satu titik di dalamnya. Triangle. java menyelesaikan ini dengan tiga panggilan ke StdDraw. line () dan satu panggilan ke StdDraw. point (). Perintah kontrol Ukuran kanvas default adalah 512-by-512 piksel dan sistem koordinat default adalah unit persegi, namun kami sering ingin menggambar plot pada skala yang berbeda. Selain itu, kita sering ingin menarik segmen garis dengan ketebalan atau titik yang berbeda dengan ukuran yang berbeda dari standar. Untuk mengakomodasi kebutuhan ini, StdDraw memiliki metode berikut: Misalnya, urutan dua panggilan menyetel koordinat gambar berada di dalam kotak yang terletak di pojok kiri bawah (x 0 y 0) dan sudut kanan atasnya adalah Di (x 1 y 1). Menyaring data ke gambar standar. PlotFilter. java membaca urutan titik yang didefinisikan oleh (x. Y) koordinat dari input standar dan menarik titik pada setiap titik. Ini mengadopsi konvensi bahwa empat nomor pertama pada input standar menentukan kotak pembatas, sehingga dapat menghitung plotnya. Merencanakan grafik fungsi. FunctionGraph. java memplot fungsi y sin (4 x) sin (20 x) pada interval (0, pi). Ada sejumlah titik yang tidak terbatas dalam interval, jadi kita harus melakukan dengan mengevaluasi fungsi pada sejumlah titik yang terbatas dalam interval tersebut. Kami sampel fungsi dengan memilih satu set x-nilai, maka komputasi y-nilai dengan mengevaluasi fungsi pada masing-masing x-nilai. Merencanakan fungsi dengan menghubungkan titik berturut-turut dengan garis menghasilkan apa yang dikenal sebagai pendekatan linear piecewise. Garis depan dan bentuk terisi. StdDraw juga mencakup metode untuk menggambar lingkaran, empat persegi panjang, dan poligon sewenang-wenang. Setiap bentuk mendefinisikan garis besar. Bila nama metode hanya bentuk nama, garis besar itu dilacak oleh pena gambar. Bila nama metode dimulai dengan diisi. Bentuk yang dinamai malah diisi padat, tidak dilacak. Argumen untuk lingkaran () menentukan lingkaran radius r argumen untuk kuadrat () menentukan kuadrat dari sisi panjang 2r berpusat pada titik yang diberikan dan argumen untuk poligon () menentukan Urutan titik yang kita hubungkan dengan garis, termasuk satu dari titik terakhir ke titik pertama. Teks dan warna. Untuk membubuhi keterangan atau menyoroti berbagai elemen dalam gambar Anda, StdDraw mencakup metode untuk menggambar teks, mengatur font, dan menyetel tinta ke pena. Dalam kode ini, java. awt. Font dan java. awt. Color adalah abstraksi yang diterapkan. Dengan tipe non primitif yang akan Anda pelajari di Bagian 3.1. Sampai saat itu, kami tinggalkan rinciannya ke StdDraw. Warna tinta default berwarna hitam adalah font default font 16-point plain Serif. Double buffering StdDraw mendukung fitur grafis komputer yang kuat yang dikenal dengan double buffering. Bila buffering ganda diaktifkan dengan memanggil enableDoubleBuffering (). Semua gambar terjadi pada kanvas di luar layar. Kanvas offscreen tidak ditampilkan hanya ada di memori komputer. Hanya saat Anda menelepon show () apakah gambar Anda bisa disalin dari kanvas di luar layar ke kanvas layar. Tempat itu ditampilkan di jendela gambar standar. Anda bisa memikirkan penyangga ganda seperti mengumpulkan semua garis, titik, bentuk, dan teks yang Anda sampaikan untuk menggambar, dan kemudian menarik semuanya secara simultan, sesuai permintaan. Salah satu alasan untuk menggunakan buffering ganda adalah untuk efisiensi saat melakukan sejumlah besar perintah gambar. Animasi komputer Penggunaan buffer ganda yang paling penting adalah menghasilkan animasi komputer. Dimana kita menciptakan ilusi gerak dengan cepat menampilkan gambar statis. Kami dapat menghasilkan animasi dengan mengulangi empat langkah berikut: Kosongkan kanvas di luar layar. Gambarlah benda-benda di layar masuk Salin kanvas di luar layar ke kanvas layar. Tunggu sebentar. Untuk mendukung langkah-langkah ini, StdDraw memiliki beberapa metode: Program Hello, World untuk animasi adalah menghasilkan bola hitam yang tampak bergerak di atas kanvas, memantul dari batas sesuai hukum tumbukan elastis. Misalkan bola berada pada posisi (x. Y) dan kami ingin menciptakan kesan memilikinya bergerak ke posisi baru, katakanlah (x 0,01, y 0,02). Kami melakukannya dalam empat langkah: Kosongkan kanvas di luar layar menjadi putih. Gambarkan bola hitam di posisi baru di kanvas di luar layar. Salin kanvas di luar layar ke kanvas layar. Tunggu sebentar. Untuk menciptakan ilusi gerakan, BouncingBall. java mengulangi langkah-langkah ini untuk keseluruhan urutan posisi bola. Gambar Perpustakaan draw standar kami mendukung gambar dan bentuk geometris. Perintah StdDraw. picture (x, y, filename) memplot gambar dalam nama file yang diberikan (format JPEG, GIF, atau PNG) pada kanvas, berpusat pada (x, y). BouncingBallDeluxe. java menggambarkan sebuah contoh dimana bola memantul digantikan oleh gambar bola tenis. Interaksi pengguna Perpustakaan draw standar kami juga menyertakan metode sehingga pengguna dapat berinteraksi dengan jendela menggunakan mouse. Contoh pertama. MouseFollower. java adalah interaksi mouse HelloWorld. Ini menarik bola biru, berpusat pada lokasi mouse. Saat pengguna menekan tombol mouse, bola berubah warna dari biru ke cyan. Penarik sederhana OneSimpleAttractor. java mensimulasikan gerak bola biru yang tertarik ke mouse. Ini juga memperhitungkan gaya tarik. Banyak penarik sederhana. SimpleAttractors. java mensimulasikan gerak 20 bola biru yang tertarik ke mouse. Ini juga memperhitungkan gaya tarik. Saat pengguna mengklik, bola menyebar secara acak. Springs. Springs. java menerapkan sistem pegas. Audio standar StdAudio adalah perpustakaan yang dapat Anda gunakan untuk memutar dan memanipulasi file suara. Ini memungkinkan Anda bermain, memanipulasi dan mensintesis suara. Kami memperkenalkan beberapa konsep dasar di balik salah satu bidang ilmu komputer dan ilmiah tertua dan paling penting: pemrosesan sinyal digital. Konser A. Konser A adalah gelombang sinus, diskalakan untuk berosilasi pada frekuensi 440 kali per detik. Fungsi sin (t) mengulanginya sendiri setiap 2pi unit pada x - axis, jadi jika kita mengukur t dalam hitungan detik dan plot fungsi sin (2pi t times 440) kita mendapatkan kurva yang berosilasi 440 kali per detik. Amplitudo (y-nilai) sesuai dengan volume. Kami menganggapnya diskalakan antara minus1 dan 1. Catatan lainnya. Rumus matematis sederhana mencirikan nada lain pada skala kromatik. Mereka dibagi rata pada skala logaritmik (basis 2): ada dua belas nada pada skala kromatik, dan kita mendapatkan catatan ke-i di atas catatan yang diberikan dengan mengalikan frekuensinya dengan kekuatan (i 12) 2. Bila Anda Dua atau dua kali frekuensi, Anda bergerak naik atau turun satu oktaf dalam skala. Misalnya 880 hertz adalah satu oktaf di atas konser A dan 110 hertz dua oktaf di bawah konser A. Sampling. Untuk suara digital, kita mewakili sebuah kurva dengan mengambil sampel secara berkala, dengan cara yang persis sama seperti ketika kita menyusun grafik fungsi. Kami mencicipi cukup sering bahwa kami memiliki representasi akurat dari curvemdasha yang menggunakan sampling rate secara luas adalah 44.100 sampel per detik. Sederhananya: kita mewakili suara sebagai deretan angka (angka sebenarnya antara minus1 dan 1). Misalnya, fragmen kode berikut memainkan konser A selama 10 detik. Mainkan lagu itu. PlayThatTune. java adalah contoh yang menunjukkan betapa mudahnya kita bisa membuat musik dengan StdAudio. Ini membutuhkan catatan dari input standar, diindeks pada skala kromatik dari konser A, dan memainkannya di audio standar. Tulis sebuah program MaxMin. java yang berbunyi dalam bilangan bulat (sebanyak yang dimasukkan pengguna) dari input standar dan mencetak nilai maksimum dan minimum. Tulis sebuah program Stats. java yang mengambil argumen baris perintah integer n. Membaca n bilangan floating-point dari input standar, dan mencetak rata-rata (nilai rata-rata) dan standar deviasi sampel (akar kuadrat dari jumlah kuadrat perbedaannya dari rata-rata, dibagi dengan n minus1). Tulis sebuah program LongestRun. java yang berbunyi dalam urutan bilangan bulat dan mencetak kedua bilangan bulat yang muncul dalam jangka waktu terlama berturut-turut dan panjang run. Misalnya, jika inputnya adalah 1 2 2 1 5 1 1 7 7 7 7 1 1. Maka program Anda harus mencetak Terpanjang berjalan: 4 7s berturut-turut. Tuliskan sebuah program WordCount. java yang terbaca dalam teks dari input standar dan mencetak jumlah kata dalam teks. Untuk tujuan latihan ini, sebuah kata adalah urutan karakter non-spasi yang dikelilingi oleh spasi. Tuliskan program Closest. java yang mengambil tiga argumen baris perintah floating-point (x, y, z), yang dibaca dari input standar urutan koordinat titik ((xi, yi, zi)), dan mencetak koordinat titik Terdekat dengan ((x, y, z)). Ingatlah bahwa kuadrat jarak antara ((x, y, z)) dan ((xi, yi, zi)) adalah ((x - xi) 2 (y - yi) 2 (z - zi) 2). Untuk efisiensi, jangan gunakan Math. sqrt () atau Math. pow (). Mengingat posisi dan massa sekuens objek, tulis sebuah program untuk menghitung pusat massa atau sentroid mereka. Centroid adalah posisi rata-rata dari n objek, terbobot oleh massa. Jika posisi dan massa diberikan oleh (xi. Yi. Mi), maka centroid (x. Y. m) diberikan oleh: Tuliskan sebuah program Centroid. java yang berbunyi dalam urutan posisi dan massa (xi. Yi. Mi) dari input standar dan mencetak pusat massa mereka (x. Y m). Petunjuk Model program anda setelah Average. java. Tulis sebuah program Checkerboard. java yang mengambil argumen baris perintah n dan plot sebuah n-by-n checkerboard dengan kotak merah dan hitam. Warna merah kiri bawah berwarna merah. Tulis sebuah program Rose. java yang mengambil argumen baris perintah n dan petak mawar dengan kelopak n (jika n aneh) atau kelopak 2n (jika n genap genap) dengan merencanakan koordinat kutub (r, theta) dari fungsi r Dosa (n kali theta) untuk theta berkisar antara 0 sampai 2pi radian. Berikut adalah output yang diinginkan untuk n 4, 7, dan 8. Tuliskan program Banner. java yang mengambil string s dari command line dan tampilkan dengan style banner di layar, bergerak dari kiri ke kanan dan membungkus kembali ke awal. Dari string sebagai akhir tercapai Tambahkan argumen baris perintah kedua untuk mengendalikan kecepatan. Tulislah sebuah program Circles. java yang menarik lingkaran penuh ukuran acak pada posisi acak di unit persegi, menghasilkan gambar seperti gambar di bawah ini. Program Anda harus mengambil empat argumen baris perintah: jumlah lingkaran, probabilitas bahwa setiap lingkaran berwarna hitam, radius minimum, dan radius maksimum. Latihan Kreatif Spirographs. Tuliskan sebuah program Spirograph. java yang mengambil tiga argumen baris perintah R, r, dan a dan menarik spirograf yang dihasilkan. Sebuah spirograph (secara teknis, epicycloid) adalah kurva yang dibentuk dengan menggulung lingkaran jari-jari r mengelilingi lingkaran tetap yang lebih besar atau radius R. Jika pena offset dari pusat lingkaran bergulir adalah (ra), maka persamaan yang dihasilkan Kurva pada waktu t diberikan oleh lekukan seperti itu dipopulerkan oleh mainan terlaris yang berisi cakram dengan gigi gigi di tepinya dan lubang kecil yang bisa Anda gunakan untuk menelusurkan spirograf. Untuk efek 3d yang dramatis, gambar melingkar, mis. Earth. gif bukan sebuah titik, dan menunjukkannya berputar dari waktu ke waktu. Berikut gambar spirograf yang dihasilkan saat R 180, r 40, dan 15. Jam. Tuliskan sebuah program Clock. java yang menampilkan animasi dari jam kedua, menit, dan jam jam analog. Gunakan metode StdDraw. show (1000) untuk mengupdate tampilan kira-kira sekali per detik. Petunjuk Ini mungkin salah satu saat langka ketika Anda ingin menggunakan operator dengan ganda - ini bekerja seperti yang Anda harapkan. Osiloskop. Tuliskan sebuah program Oscilloscope. java untuk mensimulasikan output dari sebuah osiloskop dan menghasilkan pola Lissajous. Pola ini dinamai menurut fisikawan Prancis, Jules A. Lissajous, yang mempelajari pola yang timbul ketika dua gangguan periodik saling tegak lurus terjadi secara bersamaan. Asumsikan bahwa inputnya sinusoidal, jadi persamaan parametrik berikut ini menggambarkan kurva: Ambillah enam parameter A x. W x. pajak . Theta y. W y. Dan theta y dari command line. Misalnya, gambar pertama di bawah ini memiliki Ax Ay 1, w x 2, w y 3, theta x 20 derajat, theta y 45 derajat. Yang lainnya memiliki parameter (1, 1, 5, 3, 30, 45) Web Exercise Word and line count. Modifikasi WordCount. java sehingga terbaca dalam teks dari input standar dan mencetak jumlah karakter, kata, dan baris dalam teks. Masalah curah hujan. Tuliskan sebuah program Rainfall. java yang berbunyi dalam bilangan bulat nonnegatif (mewakili curah hujan) satu per satu sampai 999999 dimasuki, dan kemudian mencetak rata-rata nilai (tidak termasuk 999999). Hapus duplikat. Tuliskan sebuah program Duplicates. java yang berbunyi dalam urutan bilangan bulat dan cetak kembali bilangan bulat, kecuali bahwa ia menghilangkan nilai berulang jika muncul secara berurutan. Misalnya, jika inputnya adalah 1 2 2 1 5 1 1 7 7 7 7 1 1, program Anda harus dicetak 1 2 1 5 1 7 1. Jalankan pengkodean panjang. Tuliskan program RunLengthEncoder. java yang mengkodekan sebuah input biner dengan menggunakan pengkodean run length. Tuliskan program RunLengthDecoder. java yang men-decode pesan yang dikodekan panjang berjalan. Kepala dan ekor Tuliskan program Head. java dan Tail. java yang mengambil input baris perintah integer N dan mencetak baris N pertama atau terakhir dari file yang diberikan. (Cetak keseluruhan file jika terdiri dari Misalnya pesan VENI, VIDI, VICI dikonversi ke YHQL, YLGL, YLFL Tulis sebuah program Caesar. java yang mengambil argumen baris perintah k dan menerapkan cipher Caesar dengan shift k to Urutan huruf dibaca dari input standar. Jika huruf bukan huruf besar, cukup cetak kembali. Caesar cipher decoding Bagaimana Anda memecahkan kode pesan yang dienkripsi menggunakan Caesar cipher Hint. Anda seharusnya tidak perlu menulis kode lagi. Matriks paritas Sebuah matriks Boolean memiliki properti paritas ketika setiap baris dan kolom masing-masing memiliki jumlah yang genap. Ini adalah jenis kode kesalahan koreksi yang sederhana karena jika satu bit rusak dalam transmisi (bit dibalik dari 0 sampai 1 atau dari 1 sampai 0) dapat dideteksi dan diperbaiki Heres file input 4 x 4 yang memiliki properti paritas: Tuliskan sebuah program ParityCheck. java yang mengambil bilangan bulat N sebagai input baris perintah dan dibaca dalam N-by-N Boolean Matriks dari input standar, dan output jika (i) matriks memiliki sifat paritas , Atau (ii) menunjukkan bit tunggal yang rusak (i, j) dapat dibalik untuk mengembalikan properti paritas, atau (iii) menunjukkan bahwa matriks tersebut rusak (lebih dari dua bit perlu diubah untuk mengembalikan properti paritas) . Gunakan sesedikit mungkin penyimpanan internal. Petunjuk: Anda bahkan tidak perlu menyimpan fungsi matriks Takagis. Plot Takagis berfungsi: di mana-mana terus menerus, tidak ada bedanya. Masalah hitchhiker Anda mewawancarai kandidat N untuk posisi tunggal American Idol. Setiap menit Anda bisa melihat kandidat baru, dan Anda punya waktu satu menit untuk memutuskan apakah akan mengumumkan orang itu American Idol atau tidak. Anda mungkin tidak berubah pikiran setelah selesai mewawancarai kandidat. Misalkan Anda bisa langsung menilai setiap kandidat dengan satu bilangan real antara 0 dan 1, tapi tentu saja, Anda tidak tahu peringkat calon yang belum terlihat. Rancang strategi dan tulis sebuah program AmericanIdol yang memiliki setidaknya 25 kemungkinan untuk memilih kandidat terbaik (dengan asumsi kandidat tiba secara acak), membaca 500 data nilai dari input standar. Solusi: wawancara untuk N2 menit dan catat rating kandidat terbaik yang terlihat sejauh ini. Di menit ke depan N2, pilih kandidat pertama yang memiliki rating lebih tinggi dari yang tercatat. Ini menghasilkan setidaknya 25 peluang karena Anda akan mendapatkan kandidat terbaik jika kandidat terbaik kedua tiba di menit N2 pertama, dan kandidat terbaik tiba di menit akhir N2. Hal ini dapat ditingkatkan sedikit menjadi 1e 0,36788 dengan menggunakan strategi yang pada dasarnya sama, namun beralih ke waktu Ne. Berlian bersarang. Tulis sebuah program Diamonds. java yang mengambil input baris perintah N dan plot kotak n dan nested Nested. Berikut adalah output yang diinginkan untuk N 3, 4, dan 5. Regular poligon. Buat fungsi untuk memplot sebuah N-gon, berpusat pada (x, y) dari panjang ukuran s. Gunakan fungsi untuk menggambar poligon bersarang seperti gambar di bawah ini. Kotak bergoyang Tuliskan program BulgingSquares. java yang menarik ilusi optik berikut dari Akiyoshi Kitaoka Pusat ini tampak menonjol keluar meskipun semua kotak berukuran sama. Mencipratkan tikus Misalkan tikus N yang mulai pada simpul poligon biasa dengan sisi N, dan masing-masing mengarah ke mouse terdekat terdekat (berlawanan arah jarum jam) sampai mereka semua bertemu. Tulis sebuah program untuk menggambar jalur spiral logaritmik yang mereka telusuri dengan menggambar N-gons bersarang, diputar dan menyusut seperti dalam animasi ini. Spiral. Tulis sebuah program untuk menggambar spiral seperti yang ada di bawah ini. Globe. Tulis sebuah program Globe. java yang mengambil argumen baris perintah nyata alfa dan plotkan pola seperti globe dengan parameter alpha. Plot koordinat polar (r, theta) dari fungsi f (theta) cos (alfa kali theta) untuk theta berkisar 0 sampai 7200 derajat. Berikut adalah output yang diinginkan untuk alpha 0.8, 0.9, dan 0.95. Menggambar string Tulis sebuah program RandomText. java yang mengambil sebuah string s dan integer N sebagai input baris perintah, dan tuliskan string N kali di lokasi acak, dan dengan warna acak. 2D berjalan acak Tuliskan sebuah program RandomWalk. java untuk mensimulasikan jalan acak 2D dan menghidupkan hasilnya. Mulai di tengah grid 2N-by-2N. Lokasi saat ini ditampilkan dalam warna biru mengikuti jejak berwarna putih. Meja berputar Anda duduk di meja persegi yang berputar (seperti Susan yang malas), dan ada empat koin yang ditempatkan di empat sudut meja. Tujuan Anda adalah untuk membalikkan koin sehingga mereka semua semua kepala atau semua ekor, di mana titik bel berbunyi untuk memberitahu Anda bahwa Anda telah selesai. Anda dapat memilih dua dari mereka, menentukan orientasi mereka, dan (secara opsional) membalik salah satu atau keduanya. Untuk membuat hal-hal yang menantang, Anda ditutup matanya, dan meja diputar setelah setiap kali Anda memilih dua koin. Tulislah sebuah program RotatingTable. java yang menginisialisasi koin ke orientasi acak. Kemudian, ia meminta pengguna untuk memilih dua posisi (1-4), dan mengidentifikasi orientasi masing-masing koin. Selanjutnya, pengguna dapat menentukan mana, jika ada dua koin yang dibalik. Proses berulang sampai pengguna memecahkan teka-teki. Pemecah meja berputar Tuliskan program lain RotatingTableSolver. java untuk memecahkan teka-teki meja berputar. Salah satu strategi yang efektif adalah memilih dua koin secara acak dan membalikkannya ke kepala. Namun, jika Anda benar-benar tidak beruntung, ini bisa mengambil sejumlah langkah yang sewenang-wenang. Tujuan: menyusun strategi yang selalu memecahkan teka-teki paling banyak dalam 5 langkah. Hex. Hex adalah permainan papan dua pemain yang dipopulerkan oleh John Nash saat menjadi mahasiswa pascasarjana di Princeton University, dan kemudian dikomersialkan oleh Parker Brothers. Ini dimainkan pada grid heksagonal dalam bentuk berlian 11-by-11. Tulis sebuah program Hex. java yang menarik papan. Gerakan proyektil dengan drag. Tuliskan sebuah program BallisticMotion. java yang memplot lintasan bola yang ditembak dengan kecepatan v pada sudut theta. Buat akun untuk gaya gravitasi dan daya tarik. Asumsikan bahwa gaya drag sebanding dengan kuadrat kecepatan. Dengan menggunakan persamaan Newtons dari motions dan metode Euler-Cromer, perbarui posisi, kecepatan, dan percepatan sesuai dengan persamaan berikut: Gunakan G 9.8, C 0.002, dan atur kecepatan awal menjadi 180 dan sudutnya menjadi 60 derajat. Jantung. Tuliskan sebuah program Heart. java untuk menggambar hati merah muda: Gambarlah sebuah berlian, lalu tarik dua lingkaran ke sisi kiri atas dan kanan atas. Mengubah kuadrat. Tulis sebuah program yang menggambar persegi dan ubah warnanya setiap detik. Gerakan harmonis sederhana. Ulangi latihan sebelumnya, tapi hidupkan pola Lissajous seperti pada applet ini. Contoh: A B w x w y 1, tapi setiap t tarikan 100 (atau lebih) poin dengan phi x berkisar antara 0 sampai 720 derajat, dan phi x berkisar antara 0 sampai 1080 derajat. Bresenhams line drawing algorithm. Untuk merencanakan segmen garis dari (x1, y1) ke (x2, y2) pada monitor, katakanlah 1024-by-1024, Anda perlu membuat perkiraan diskrit pada garis kontinu dan menentukan dengan tepat piksel mana yang akan dihidupkan. Algoritma garis penunjuk Bresenhams adalah solusi cerdas yang bekerja bila kemiringannya antara algoritma 0 dan 1 dan x1 Modify Bresenhams untuk menangani segmen garis acak. Gila millers Tulis sebuah program Madness. java untuk merencanakan persamaan parametrik: di mana parameter t ada di radian. Anda harus mendapatkan gambaran kompleks berikut ini. Percobaan dengan mengubah parameter dan menghasilkan gambar asli. Fay kupu-kupu. Tuliskan sebuah program Butterfly. java untuk merencanakan persamaan kutub: di mana parameter t ada di radian. Anda harus mendapatkan gambar seperti sosok seperti kupu-kupu berikut. Percobaan dengan mengubah parameter dan menghasilkan gambar asli. Database siswa File students. txt berisi daftar siswa yang terdaftar di kelas sains pengantar komputer di Princeton. Baris pertama berisi bilangan bulat N yang menentukan jumlah siswa dalam database. Masing-masing baris N berikut terdiri dari empat informasi, dipisahkan oleh spasi: nama depan, nama belakang, alamat email, dan nomor bagian. Program Students. java dibaca di bilangan N dan N kemudian N dari data input standar, menyimpan data dalam empat array sejajar (array integer untuk nomor bagian dan array string untuk bidang lainnya). Kemudian, program tersebut membuat daftar siswa di bagian 4 dan 5. Shuffling. Pada pemilihan runoff negara bagian tanggal 7 Oktober 2003 di Venezuela untuk gubernur, ada 135 kandidat resmi. Untuk menghindari prasangka alami terhadap kandidat yang namanya muncul di akhir alfabet (Jon W. Zellhoefer), pejabat pemilihan California berusaha untuk memesan kandidat secara acak. Tulis sebuah program program Shuffle. java yang mengambil argumen baris perintah N, berbunyi dalam N string dari input standar, dan mencetaknya kembali dalam urutan yang dikocok. (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. Hint . 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. De spite 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. There are many others. 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 the n 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