The document discusses elementary sorting algorithms including selection sort, insertion sort, and shellsort. It provides examples of how sorting can be used to sort various data types like numbers, strings, and files by implementing callbacks that allow the sorting routines to compare objects. The key point is that sorting routines do not need specific information about the types of objects being sorted since clients can pass a compare method through an interface like Comparable.
Shellsort improves on insertion sort by allowing exchanges of elements that are farther apart, breaking the data into "shells" with gaps between elements that can be swapped. This allows distant elements that may be out of order to be shifted into place before fine-tuning the sort with successively smaller gaps.
To learn about the basic concepts of Object Oriented Programming and Inheritance plus different Inheritance Models and interview questions will be covered.
The document discusses various types of arrays in Java, including one-dimensional arrays, multi-dimensional arrays, and jagged arrays. It explains how to declare, initialize, access, and pass array elements. Key points include that arrays are dynamically allocated objects that can store primitive values or objects, arrays inherit from Object and implement Serializable and Cloneable, and the class name of an array returns [ followed by the data type (e.g. [I for int array). The document also demonstrates various array examples using for loops and exceptions like ArrayIndexOutOfBoundsException.
Collection Framework in Java | Generics | Input-Output in Java | Serializatio...Sagar Verma
Collection Framework in Java,Generics,Input-Output in Java,Serialization,Inner Classes
Collection Framework in Java
The Collections Framework - Set Interface- List Interface - Map Interface - Queue Interface -Sorting collections using utility methods
equals () and hash Code contract in Java collections
Overriding equals and hash Code methods in Java
Generics
Generics for Collections, class and methods
Input-Output in Java
What is a stream? ,Bytes vs. Characters, Java IO API ,Reading a file; writing to a file using various APIs
Reading User input from console , PrintWriter Class
Serialization
Object Serialization , Serializable Interface , De-Serializable
Inner Classes
Inner Classes ,Member Classes, Local Classes, Anonymous Classes, Static Nested Classes
Modern Compiler Design Java Tutorial provides an overview of object-oriented programming concepts in Java including objects, classes, inheritance, encapsulation, and polymorphism. It also covers key Java features like packages, access control modifiers, exceptions, input/output streams, and collections. The document is intended as an introduction to Java for programmers familiar with C++.
Modul untuk Praktikum Pengolahan Database di Java dengan menggunakan konsep OOP Mata Pelajaran Pemrograman Internet dengan Java-JSP SMK Telkom Sandhy Putra Malang
This document discusses constructors and destructors in C# classes. It explains that objects must be instantiated using the "new" keyword before their methods can be called. Static methods can be called directly on the class without creating an object instance. Instance variables are unique to each object, while static variables are shared among all objects of a class. The document uses several code examples to demonstrate how to properly create object instances and call both static and instance methods and variables.
This document provides information on input/output operations, file handling, and serialization in Java. It discusses Java's input and output streams for reading and writing bytes and characters. It describes classes for working with files like File, FileInputStream, FileOutputStream, FileReader, and FileWriter. Examples are given for reading from and writing to files and the console. The document also introduces serialization in Java for converting objects to byte streams for storage or transmission.
Shellsort improves on insertion sort by allowing exchanges of elements that are farther apart, breaking the data into "shells" with gaps between elements that can be swapped. This allows distant elements that may be out of order to be shifted into place before fine-tuning the sort with successively smaller gaps.
To learn about the basic concepts of Object Oriented Programming and Inheritance plus different Inheritance Models and interview questions will be covered.
The document discusses various types of arrays in Java, including one-dimensional arrays, multi-dimensional arrays, and jagged arrays. It explains how to declare, initialize, access, and pass array elements. Key points include that arrays are dynamically allocated objects that can store primitive values or objects, arrays inherit from Object and implement Serializable and Cloneable, and the class name of an array returns [ followed by the data type (e.g. [I for int array). The document also demonstrates various array examples using for loops and exceptions like ArrayIndexOutOfBoundsException.
Collection Framework in Java | Generics | Input-Output in Java | Serializatio...Sagar Verma
Collection Framework in Java,Generics,Input-Output in Java,Serialization,Inner Classes
Collection Framework in Java
The Collections Framework - Set Interface- List Interface - Map Interface - Queue Interface -Sorting collections using utility methods
equals () and hash Code contract in Java collections
Overriding equals and hash Code methods in Java
Generics
Generics for Collections, class and methods
Input-Output in Java
What is a stream? ,Bytes vs. Characters, Java IO API ,Reading a file; writing to a file using various APIs
Reading User input from console , PrintWriter Class
Serialization
Object Serialization , Serializable Interface , De-Serializable
Inner Classes
Inner Classes ,Member Classes, Local Classes, Anonymous Classes, Static Nested Classes
Modern Compiler Design Java Tutorial provides an overview of object-oriented programming concepts in Java including objects, classes, inheritance, encapsulation, and polymorphism. It also covers key Java features like packages, access control modifiers, exceptions, input/output streams, and collections. The document is intended as an introduction to Java for programmers familiar with C++.
Modul untuk Praktikum Pengolahan Database di Java dengan menggunakan konsep OOP Mata Pelajaran Pemrograman Internet dengan Java-JSP SMK Telkom Sandhy Putra Malang
This document discusses constructors and destructors in C# classes. It explains that objects must be instantiated using the "new" keyword before their methods can be called. Static methods can be called directly on the class without creating an object instance. Instance variables are unique to each object, while static variables are shared among all objects of a class. The document uses several code examples to demonstrate how to properly create object instances and call both static and instance methods and variables.
This document provides information on input/output operations, file handling, and serialization in Java. It discusses Java's input and output streams for reading and writing bytes and characters. It describes classes for working with files like File, FileInputStream, FileOutputStream, FileReader, and FileWriter. Examples are given for reading from and writing to files and the console. The document also introduces serialization in Java for converting objects to byte streams for storage or transmission.
Woxa Technologies have great industrial exoerts in java field they work on the live projects with students they are not teacher they are industrial trainer.
for more information 8471003400
ZeroSpace is a part of Woxa Technology where industrial trainer are ready to trained you.Take a demo class and choose your future in the programming field. We offer to learn in latest technology with live project which is demanding.
feel free to contact us-: 8471003400
This document provides an overview of Java collections APIs, including:
- A history of collections interfaces added in different JDK versions from 1.0 to 1.7.
- Descriptions of common collection interfaces like List, Set, Map and their implementations.
- Comparisons of performance and characteristics of different collection implementations.
- Explanations of common collection algorithms and concurrency utilities.
- References for further reading on collections and concurrency.
The Ring programming language version 1.4.1 book - Part 9 of 31Mahmoud Samir Fayed
This document summarizes reflection and meta-programming functions in the Ring programming language. It describes functions to get information about code at runtime like variable names, functions, classes and more. It also describes functions to check and modify objects, like getting/adding attributes, checking if an attribute exists, and more. These meta-programming capabilities allow Ring programs to introspect and modify their own code and objects at runtime.
Joose is a meta object system for JavaScript that allows developers to write well-structured, expressive, declarative, and maintainable JavaScript applications using classes, interfaces, mixins, modules and other object-oriented programming features. It aims to bring features from languages like Java, C#, Smalltalk, CLOS, Ruby, and Perl 5/6 to JavaScript in a native way. Joose provides a declarative syntax for defining these features and also includes meta features for introspecting and manipulating the defined classes and objects.
Object Oriented Programming (OOP) allows developers to organize complex programs using classes and objects. OOP uses concepts like encapsulation, inheritance and polymorphism to keep data and functionality together in objects. The basic building blocks in OOP are classes, which define the properties and methods of an object, and objects, which are instances of classes. Classes can inherit properties and methods from parent classes, and objects can be identified and compared using operators like instanceof. Magic methods allow objects to override default behavior for operations like property access, method calling and object destruction.
This document discusses Java generics. Some key points:
- Generics allow data type parameters to be used for classes, interfaces, and methods. This allows code to work with different data types.
- Generics were introduced in JDK 5 and support abstraction over types. The class/method designer can define generic types, while users provide the specific types.
- Common uses of generics include the Java Collection Framework and auto-boxing/unboxing of primitives and wrappers.
- Generics help reuse code by allowing classes, interfaces, and methods to work with different object types. They do not support primitive types like int directly.
- Examples demonstrate generic classes, interfaces, methods,
This document provides an overview of Java generics through examples. It begins with simple examples demonstrating how generics can be used to define container classes (BoxPrinter) and pair classes (Pair). It discusses benefits like type safety and avoiding duplication. Further examples show generics with methods and limitations like erasure. Wildcard types are presented as a way to address subtyping issues. In general, generics provide flexibility in coding but their syntax can sometimes be complex to read.
This document provides information about various concepts related to classes in C++, including defining a class, creating objects, special member functions like constructors and destructors, implementing class methods, accessing class members, and class abstraction. It defines a Circle class with private data member radius and public member functions to set and get radius and calculate diameter, area, and circumference. It demonstrates defining member functions inside and outside the class and using operators like dot and arrow to access class members.
Object oriented programming with pythonArslan Arshad
A short intro to how Object Oriented Paradigm work in Python Programming language. This presentation created for beginner like bachelor student of Computer Science.
The document provides information about a JavaScript course including:
1. The course consists of 5 lectures and 5 labs and is evaluated based on projects, assignments, labs and quizzes.
2. The lecture outline covers introduction to JavaScript, syntax, built-in objects and functions.
3. JavaScript was invented by Brendan Eich at Netscape and first appeared in the Netscape Navigator browser in 1995.
The document discusses different types of data members and member functions in classes in C++, including constant, mutable, and static data members, as well as constant, static, overloaded, and inline member functions. It provides examples of how to declare and use these various data members and member functions. It also covers topics like constant member functions, static data members, nested member functions, friend functions and classes, array of objects, and passing objects to functions by value, reference, and pointer.
Classes extend the built-in capabilities of C++ able you in representing and solving complex, real-world problems. A class is an organization of data and functions which operate on them. Data structures are called data members and the functions are called member functions, the combination of data members and member functions constitute a data
object or simply an object.
Class is a group of data member and member functions. Another word class is a collection of objects of similar type.
To create a class, use the class keyword followed by a name for the object. Like any other declared variable, the class declaration ends with a semi-colon. The name of a class follows the rules we have applied for variable and function names.
The document discusses defining programmer-defined classes in Java. It provides an example of defining a Bicycle class with data members and methods, and using it to track bicycle ownership. It then expands on this example by defining an Account class and using both classes in a sample program. The key aspects covered include defining classes, using visibility modifiers, passing objects to methods, and differentiating local variables from data members and parameters.
This document discusses classes and objects in C++. It defines a class as a user-defined data type that implements an abstract object by combining data members and member functions. Data members are called data fields and member functions are called methods. An abstract data type separates logical properties from implementation details and supports data abstraction, encapsulation, and hiding. Common examples of abstract data types include Boolean, integer, array, stack, queue, and tree structures. The document goes on to describe class definitions, access specifiers, static members, and how to define and access class members and methods.
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAMaulik Borsaniya
Classes and Object-oriented Programming:
Classes: Creating a Class, The Self Variable, Constructor, Types of Variables, Namespaces, Types of Methods (Instance Methods, Class Methods, Static Methods), Passing Members of One Class to Another Class, Inner Classes
Inheritance and Polymorphism: Constructors in Inheritance, Overriding Super Class Constructors and Methods, The super() Method, Types of Inheritance, Single Inheritance, Multiple Inheritance, Method Resolution Order (MRO), Polymorphism, Duck Typing Philosophy of Python, Operator Overloading, Method Overloading, Method Overriding
Abstract Classes and Interfaces: Abstract Method and Abstract Class, Interfaces in Python, Abstract Classes vs. Interfaces,
The document discusses the evolution of the Java platform, including new features in Java SE 7 and Java SE 8. Some key changes in Java SE 7 include better integer literals, string switches, simplified generics using diamond operator, and automatic resource management. Java SE 8 will focus on invokedynamic for multi-language support on the JVM and method handles. The JVM specification defines the runtime environment independently of the Java programming language.
This document provides an overview of key concepts in the Java programming language, including:
- Java is an object-oriented language that is simpler than C++ and supports features like platform independence.
- The Java development environment includes tools for compiling, debugging, and running Java programs.
- Java programs work with basic data types like int and double, as well as user-defined classes, variables, and arrays.
- The document explains operators, control structures, formatting output, and the basics of classes and objects in Java.
This document provides an overview of Java collections and common collection interfaces like List, Set, Map, Queue, and their implementations. It discusses the core collection interfaces like Collection, List, Set, Map, Queue, and their methods. Specific implementations of these interfaces are covered like ArrayList, LinkedList, HashSet, TreeSet, HashMap, TreeMap, PriorityQueue. The document is presented by Ravi Kant Sahu, Assistant Professor at Lovely Professional University in Punjab, India and provides details on using collections in Java.
Insertion sort works by iterating through a list and inserting each element into its sorted position. It makes space by shifting larger elements to the right. For a randomly ordered array, insertion sort performs on average N2/4 key comparisons and exchanges in the worst case. However, it performs very efficiently on already sorted or partially sorted lists, requiring linear time. Insertion sort is well-suited for datasets where elements are mostly sorted or for very small lists.
The document discusses sorting and searching algorithms. It introduces sorting as a way to make searching faster. Linear search and binary search are described as ways to search through unsorted and sorted lists, respectively. Common sorting algorithms like selection sort, insertion sort, and Shellsort are explained. Selection sort and insertion sort have quadratic runtimes while Shellsort is subquadratic. Maintaining stability is also discussed as a property of some sorting algorithms.
Woxa Technologies have great industrial exoerts in java field they work on the live projects with students they are not teacher they are industrial trainer.
for more information 8471003400
ZeroSpace is a part of Woxa Technology where industrial trainer are ready to trained you.Take a demo class and choose your future in the programming field. We offer to learn in latest technology with live project which is demanding.
feel free to contact us-: 8471003400
This document provides an overview of Java collections APIs, including:
- A history of collections interfaces added in different JDK versions from 1.0 to 1.7.
- Descriptions of common collection interfaces like List, Set, Map and their implementations.
- Comparisons of performance and characteristics of different collection implementations.
- Explanations of common collection algorithms and concurrency utilities.
- References for further reading on collections and concurrency.
The Ring programming language version 1.4.1 book - Part 9 of 31Mahmoud Samir Fayed
This document summarizes reflection and meta-programming functions in the Ring programming language. It describes functions to get information about code at runtime like variable names, functions, classes and more. It also describes functions to check and modify objects, like getting/adding attributes, checking if an attribute exists, and more. These meta-programming capabilities allow Ring programs to introspect and modify their own code and objects at runtime.
Joose is a meta object system for JavaScript that allows developers to write well-structured, expressive, declarative, and maintainable JavaScript applications using classes, interfaces, mixins, modules and other object-oriented programming features. It aims to bring features from languages like Java, C#, Smalltalk, CLOS, Ruby, and Perl 5/6 to JavaScript in a native way. Joose provides a declarative syntax for defining these features and also includes meta features for introspecting and manipulating the defined classes and objects.
Object Oriented Programming (OOP) allows developers to organize complex programs using classes and objects. OOP uses concepts like encapsulation, inheritance and polymorphism to keep data and functionality together in objects. The basic building blocks in OOP are classes, which define the properties and methods of an object, and objects, which are instances of classes. Classes can inherit properties and methods from parent classes, and objects can be identified and compared using operators like instanceof. Magic methods allow objects to override default behavior for operations like property access, method calling and object destruction.
This document discusses Java generics. Some key points:
- Generics allow data type parameters to be used for classes, interfaces, and methods. This allows code to work with different data types.
- Generics were introduced in JDK 5 and support abstraction over types. The class/method designer can define generic types, while users provide the specific types.
- Common uses of generics include the Java Collection Framework and auto-boxing/unboxing of primitives and wrappers.
- Generics help reuse code by allowing classes, interfaces, and methods to work with different object types. They do not support primitive types like int directly.
- Examples demonstrate generic classes, interfaces, methods,
This document provides an overview of Java generics through examples. It begins with simple examples demonstrating how generics can be used to define container classes (BoxPrinter) and pair classes (Pair). It discusses benefits like type safety and avoiding duplication. Further examples show generics with methods and limitations like erasure. Wildcard types are presented as a way to address subtyping issues. In general, generics provide flexibility in coding but their syntax can sometimes be complex to read.
This document provides information about various concepts related to classes in C++, including defining a class, creating objects, special member functions like constructors and destructors, implementing class methods, accessing class members, and class abstraction. It defines a Circle class with private data member radius and public member functions to set and get radius and calculate diameter, area, and circumference. It demonstrates defining member functions inside and outside the class and using operators like dot and arrow to access class members.
Object oriented programming with pythonArslan Arshad
A short intro to how Object Oriented Paradigm work in Python Programming language. This presentation created for beginner like bachelor student of Computer Science.
The document provides information about a JavaScript course including:
1. The course consists of 5 lectures and 5 labs and is evaluated based on projects, assignments, labs and quizzes.
2. The lecture outline covers introduction to JavaScript, syntax, built-in objects and functions.
3. JavaScript was invented by Brendan Eich at Netscape and first appeared in the Netscape Navigator browser in 1995.
The document discusses different types of data members and member functions in classes in C++, including constant, mutable, and static data members, as well as constant, static, overloaded, and inline member functions. It provides examples of how to declare and use these various data members and member functions. It also covers topics like constant member functions, static data members, nested member functions, friend functions and classes, array of objects, and passing objects to functions by value, reference, and pointer.
Classes extend the built-in capabilities of C++ able you in representing and solving complex, real-world problems. A class is an organization of data and functions which operate on them. Data structures are called data members and the functions are called member functions, the combination of data members and member functions constitute a data
object or simply an object.
Class is a group of data member and member functions. Another word class is a collection of objects of similar type.
To create a class, use the class keyword followed by a name for the object. Like any other declared variable, the class declaration ends with a semi-colon. The name of a class follows the rules we have applied for variable and function names.
The document discusses defining programmer-defined classes in Java. It provides an example of defining a Bicycle class with data members and methods, and using it to track bicycle ownership. It then expands on this example by defining an Account class and using both classes in a sample program. The key aspects covered include defining classes, using visibility modifiers, passing objects to methods, and differentiating local variables from data members and parameters.
This document discusses classes and objects in C++. It defines a class as a user-defined data type that implements an abstract object by combining data members and member functions. Data members are called data fields and member functions are called methods. An abstract data type separates logical properties from implementation details and supports data abstraction, encapsulation, and hiding. Common examples of abstract data types include Boolean, integer, array, stack, queue, and tree structures. The document goes on to describe class definitions, access specifiers, static members, and how to define and access class members and methods.
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAMaulik Borsaniya
Classes and Object-oriented Programming:
Classes: Creating a Class, The Self Variable, Constructor, Types of Variables, Namespaces, Types of Methods (Instance Methods, Class Methods, Static Methods), Passing Members of One Class to Another Class, Inner Classes
Inheritance and Polymorphism: Constructors in Inheritance, Overriding Super Class Constructors and Methods, The super() Method, Types of Inheritance, Single Inheritance, Multiple Inheritance, Method Resolution Order (MRO), Polymorphism, Duck Typing Philosophy of Python, Operator Overloading, Method Overloading, Method Overriding
Abstract Classes and Interfaces: Abstract Method and Abstract Class, Interfaces in Python, Abstract Classes vs. Interfaces,
The document discusses the evolution of the Java platform, including new features in Java SE 7 and Java SE 8. Some key changes in Java SE 7 include better integer literals, string switches, simplified generics using diamond operator, and automatic resource management. Java SE 8 will focus on invokedynamic for multi-language support on the JVM and method handles. The JVM specification defines the runtime environment independently of the Java programming language.
This document provides an overview of key concepts in the Java programming language, including:
- Java is an object-oriented language that is simpler than C++ and supports features like platform independence.
- The Java development environment includes tools for compiling, debugging, and running Java programs.
- Java programs work with basic data types like int and double, as well as user-defined classes, variables, and arrays.
- The document explains operators, control structures, formatting output, and the basics of classes and objects in Java.
This document provides an overview of Java collections and common collection interfaces like List, Set, Map, Queue, and their implementations. It discusses the core collection interfaces like Collection, List, Set, Map, Queue, and their methods. Specific implementations of these interfaces are covered like ArrayList, LinkedList, HashSet, TreeSet, HashMap, TreeMap, PriorityQueue. The document is presented by Ravi Kant Sahu, Assistant Professor at Lovely Professional University in Punjab, India and provides details on using collections in Java.
Insertion sort works by iterating through a list and inserting each element into its sorted position. It makes space by shifting larger elements to the right. For a randomly ordered array, insertion sort performs on average N2/4 key comparisons and exchanges in the worst case. However, it performs very efficiently on already sorted or partially sorted lists, requiring linear time. Insertion sort is well-suited for datasets where elements are mostly sorted or for very small lists.
The document discusses sorting and searching algorithms. It introduces sorting as a way to make searching faster. Linear search and binary search are described as ways to search through unsorted and sorted lists, respectively. Common sorting algorithms like selection sort, insertion sort, and Shellsort are explained. Selection sort and insertion sort have quadratic runtimes while Shellsort is subquadratic. Maintaining stability is also discussed as a property of some sorting algorithms.
Metode insertion sort mengurutkan elemen dalam array dengan membandingkan elemen yang sedang dibaca dengan elemen di sisi kirinya yang sudah terurut, kemudian menyisipkan elemen yang sedang dibaca pada posisi yang tepat.
This document discusses insertion sort, including its pseudocode, time and space complexity analysis. It shows that insertion sort has an overall time complexity of O(n^2) as its worst case performance involves n-1 passes through the inner loop, with each pass taking up to n-1 comparisons. While O(n^2) is practical for small inputs, faster algorithms may be needed for large problem sizes due to hardware limitations. Algorithmic improvements are generally more effective than relying on increased computer speeds alone.
The document discusses insertion sort, a simple sorting algorithm that builds a sorted output list from an input one element at a time. It is less efficient on large lists than more advanced algorithms. Insertion sort iterates through the input, at each step removing an element and inserting it into the correct position in the sorted output list. The best case for insertion sort is an already sorted array, while the worst is a reverse sorted array.
Insertion sort is a simple sorting algorithm that works by building a sorted array from left to right by inserting each element into its sorted position. It is more efficient for smaller data sets but less efficient for larger data sets compared to other algorithms like merge sort. Merge sort works by dividing an array into halves, recursively sorting the halves, and then merging the sorted halves into a single sorted array.
The document describes the insertion sort algorithm sorting the array [15, 9, 9, 10, 12, 1, 11, 3, 9]. It works by taking each element from the unsorted part of the array and inserting it into the correct position in the sorted part. It iterates through the array, swapping elements if the current element is less than the element preceding it, until the subarray is sorted.
The document describes various sorting algorithms, including insertion sort, selection sort, and shell sort. It provides pseudocode examples and explanations of how each algorithm works to sort a list of numbers in ascending order. Insertion sort works by taking each element and inserting it into the sorted position within the growing sorted sublist. Shell sort improves on insertion sort by sorting elements spaced further apart before sorting adjacent elements.
Introduction to data structures and AlgorithmDhaval Kaneria
This document provides an introduction to algorithms and data structures. It defines algorithms as step-by-step processes to solve problems and discusses their properties, including being unambiguous, composed of a finite number of steps, and terminating. The document outlines the development process for algorithms and discusses their time and space complexity, noting worst-case, average-case, and best-case scenarios. Examples of iterative and recursive algorithms for calculating factorials are provided to illustrate time and space complexity analyses.
Important java programs(collection+file)Alok Kumar
The document contains 6 Java programming questions and solutions:
1. A program to find unique and duplicate items in an array.
2. A Product class with properties and methods to sort objects.
3. A program to merge contents of two text files into a third file.
4. A program to count the occurrences of specific words in a file.
5. A program to read a file, add contents to an ArrayList, and write to a new file.
6. A program to print consecutive characters in a string and their frequency.
The document provides an overview of key Java concepts including:
1) Classes and methods define the structure and behaviors of objects in Java. Data types include primitives and object references.
2) Control statements like if/else and loops operate similarly to other languages like C++. Object-oriented concepts include inheritance, polymorphism, and encapsulation.
3) Interfaces define common behaviors without implementation, while abstract classes can contain abstract and implemented methods. The Java Virtual Machine executes Java bytecode making programs platform independent.
This document provides an overview of object-oriented programming concepts in Java. It discusses the differences between procedural and object-oriented programming, with OOP comprising objects that communicate with each other. The main OOP concepts covered are objects, classes, inheritance, and encapsulation. Objects have an identity, attributes, and services. Inheritance allows subclasses to inherit and extend superclass attributes and behaviors. Encapsulation separates an object's internal state from its external interface. The document also discusses other Java topics like interfaces, collections framework, exceptions, and final keywords.
This presentation contains a quick tour in Python world. First by By comparing Java code, and the equivalent Python side by side, Second by listing some cool features in Python, finally by listing downs and ups of Python in usage; when to use python and when not.
Core java by a introduction sandesh sharmaSandesh Sharma
This document provides an overview of core Java concepts including primitive types, wrappers, static methods and blocks, strings, abstract classes and interfaces, collections, equals and hashcode methods, and threads. It defines each concept, provides examples of usage, and notes key behaviors and properties. The document serves as a reference for fundamental Java programming concepts.
This document discusses various Java concepts like object-oriented programming, compilation, the main method signature, command line arguments, byte code checking, type casting, and input/output in Java using classes like DataInputStream and Scanner. It provides code examples for accepting user input using these classes and parsing the input into different data types like integer and float. It also compares DataInputStream and Scanner, noting that Scanner avoids the need to manually convert input types.
This document provides code examples demonstrating various Java GUI components and concepts including:
1. Creating a basic GUI with labels, text fields, and buttons laid out in a JPanel container.
2. Adding a menu bar with drop down menus and menu items.
3. Creating a tabbed pane interface with two JPanels as separate tabs.
4. Examples of inheritance, polymorphism, and other OOP concepts are provided throughout the code snippets.
This document provides code examples demonstrating various Java GUI components and concepts including:
1. Creating a basic GUI with labels, text fields, and buttons laid out in a JPanel container.
2. Adding a menu bar with drop down menus and menu items.
3. Creating a tabbed pane interface with two JPanels as separate tabs.
4. Examples of inheritance, polymorphism, and other OOP concepts are provided throughout the code snippets.
The document discusses Java streams and I/O. It defines streams as abstract representations of input/output devices that are sources or destinations of data. It describes byte and character streams, the core stream classes in java.io, predefined System streams, common stream subclasses, reading/writing files and binary data with byte streams, and reading/writing characters with character streams. It also covers object serialization/deserialization and compressing files with GZIP.
This document contains a lab manual for an Object Oriented Programming class through Java. It provides examples of Java programs to solve problems related to various topics in OOP including quadratic equations, Fibonacci sequences, prime numbers, matrix multiplication, file handling, stacks, infix to postfix conversion, and postfix expression evaluation. The programs are organized into weekly labs covering topics such as classes and objects, arrays, strings, file I/O, and data structures.
Arrays are collections of similar type of elements stored in contiguous memory locations. Java arrays are fixed in size and indexed starting from 0. Arrays allow for random access of elements and code optimization. Common array types include single dimensional and multidimensional arrays. Single dimensional arrays store elements in a linear list while multidimensional arrays can be thought of as tables with rows and columns. Strings in Java are objects that are immutable, meaning their values cannot be modified after creation.
Jug trojmiasto 2014.04.24 tricky stuff in java grammar and javacAnna Brzezińska
This document discusses various language tricks and quirks in Java, including:
1) The "&" operator can be used for casting lambdas to make them serializable or satisfy multiple interfaces as type bounds for generics.
2) The "|" operator allows catching multiple exception types in a single catch block, introduced in JDK7.
3) Hexadecimal floating point literals avoid decimal rounding issues.
4) String literals can be used in switch statements starting in JDK7.
5) Lambda functions were introduced in JDK8, including recursion, method references, and serialization tricks.
6) Some compiler quirks are discussed related to generics and autoboxing behavior.
The document contains code snippets from 3 weekly coding assignments:
1) A Java program to check if a string is a palindrome. It compares characters at the beginning and end of the string.
2) A Java program to sort a list of names in ascending order using string comparison and swapping.
3) A Java program to count the frequency of words in a given text by tokenizing, sorting, and printing the words.
This document provides an overview of Java programming concepts covered in a course. It discusses:
- Sections of the course covering topics like Applets, Multithreading, AWT, Swing, Networking and JDBC.
- A brief history of Java and its versions.
- Core Java concepts like objects, classes, inheritance, interfaces, strings and exceptions.
- Other features like being platform independent, secure, robust and portable.
- Data types, operators, methods, constructors, access modifiers and this keyword in Java.
This document discusses Java concurrency. It begins with an agenda and then covers key topics like shared state, thread safety, concurrency problems and symptoms, and Java concurrency methods. Facts about processors, caches and memory interactions that can impact concurrency are presented. Examples are provided to illustrate concurrency issues like visibility and atomicity. Common concurrency problems like invalid states and their symptoms are outlined. Finally, Java concurrency methods like thread confinement, immutability, volatile variables, and synchronized are defined and code examples are shown.
I need help with this code working Create another project and add yo.pdffantoosh1
I need help with this code working Create another project and add your jar file in this project. In
the main method of App class of this second project test your MyArrayList class. It is mandatory
to follow the instructions to get full credit. You need to perform the following actions. 1. Create
five strings, A1",,'B2",,'C3",'D4",'E5" 2. Save these Strings in your MyArrayList 3. Print a
message "Displaying List" 4. Display the list 5. Insert another String in your MyArrayList at
location 2 6. Print a message "Inserting Item" 7. Display the list 8. Remove String at location 0 9.
Print a message "Removing Item" 10. Display the list 11. Print a message "Setting a String" 12.
Set a new String in location 1 13. Display the list 14. Check whether "D4" is present in the list or
not, print an appropriate message 15. Find the index of "E5" in your list, print an appropriate
message 16. Print a message "Emptying List" 17. Empty the list 18. Print the size of the list
These steps check most of your MyArrayList functionality. I will also perform my own checks of
your code while grading. Deliverable: a. Copy the utils.jar file in your project folder. b. Make a
zip file of full project, not the src folder only or java files only. c. Submit the zip file. Grading
Rubric: The project is not submitted as required: 0 points
st.java J MyArrayList.java 2 J App.java 2 J MyFile.java 2 rc >J MyArrayList.java >q&
MyArrayList > get(int) public class MyArrayList implements MyList \{ Object [] obj = new
Object [1]; int size; public int size()\{ return size; \} public object get(int index) if (index <0
index >= size ){// throw new indexo return obj [index]; \} return index; // this should be deleted
after public void add (Object 0 ) \{ //if this test fails there is a space in the array. // it will pass
itself. if ( size == obj. length ){ Object [] obj2 = new 0 bject [obj. length 2]; for(int i=0;i<0bj.
length; i++){ obj2[i]=obj [i] ; \} obj=obj2; \} obj [ size ]=0; size++; \} public void add(int index,
Object o) \{ if(index > size || index <0 ) \{ throw new IndexOut0fBoundsException(index); \} if
(size == obj. length ){ Object [] obj2 = new Object [obj. length 2 ]; for(int i=0;i<0bj. length;
i++){ obj 2[i]=obj[i]; \} obj=obj2; \} if (index i=size;i>= index; i){ nhi [i=nhii1 : Ln 16, Col 56
Spaces: 4 UTF-8 LF \{\} Java
In this lab you will add an interface to the MyUtils project, and implement it in your
MyArrayList class in the MyUtils project. You will test the newly added functionality of your
MyArrayList class in another project. The UML for the Interface is as follows S Description of
methods Following method are self-explanatory: size(), get(int index), add (object o), remove
(int index), and isEmpty). Below is the description of all other methods. void add(int index,
Object o) inserts the given reference of object o at location index, making all entries move down
a spot. void remove (Object o) removes the first occurrence of object o in the list, moving all
entries .
The document discusses test-driven development (TDD) and refactoring. It provides examples of unit test fixtures, exercising the system under test (SUT), and verifying results. It also discusses refactoring code to remove smells like duplicated code through techniques like extracting methods. The goal is to use TDD to write code that works and is clean through small, incremental changes while ensuring it continues to work by passing all tests.
This document provides an overview of basic Java syntax including:
- How to create, compile, and execute simple Java programs
- Using arrays, loops, if/else statements, and comparing strings
- Building one-dimensional and multi-dimensional arrays
- Common data structures like Vector and Hashtable
- Errors handling and the Collections Framework
This document provides an overview of object-oriented programming concepts in Java including:
- Objects communicate by sending and receiving messages. A program is composed of objects that interact.
- The main concepts of object-oriented programming are objects, classes, inheritance, and encapsulation.
- A class defines the type of an object and groups similar objects. An object is an instance of a class.
- Inheritance allows subclasses to inherit and extend the behavior of superclasses through generalization and specialization.
- Encapsulation separates the internal state of an object from its external interface through access control and information hiding.
The document is an untitled HTML file that consists of 19 numbered pages without any visible text or content. It appears to be an empty or incomplete document.
The document is an untitled 32-page file that provides no substantive information. It consists of repetitive page number listings without any descriptive text, headings, or other content.
This very short document contains random text and does not convey any clear ideas or information in a meaningful way. It consists of only a phrase and multiple repeated characters with no context provided.
This very short document contains random text and does not convey any clear ideas or information in a meaningful way. It consists of only a phrase and various repetitions of the letter "h" without any connecting context or explanation. Therefore, no accurate high-level summary can be provided in 3 sentences or less.
Stacks are a new feature in Mac OS X Leopard that allow you to access frequently used files directly from the Dock. Dragging a folder to the right side of the Dock creates a stack. Stacks can be viewed as a fan or grid and allow easy access and organization of files. Customization options exist for sorting and viewing stacks.
Stacks are a new feature in Mac OS X Leopard that allow you to access frequently used files directly from the Dock. Stacks can be created by dragging any folder to the right side of the Dock. Clicking a stack will display its contents in either a fan or grid layout. Files can be added or removed from stacks by dragging them in or out. The Documents and Downloads stacks are pre-made for organizing common file types.
Stacks are a new feature in Mac OS X Leopard that allow you to access frequently used files directly from the Dock. Dragging a folder to the right side of the Dock creates a stack. Stacks can be viewed as a fan or grid and allow easy access and organization of files. Customization options exist for sorting and viewing stacks.
Stacks are a new feature in Mac OS X Leopard that allow you to access frequently used files directly from the Dock. Dragging a folder to the right side of the Dock creates a stack. Stacks can be viewed as a fan or grid and allow easy access and organization of files. Customization options exist for sorting and viewing stacks.
Stacks are a new feature in Mac OS X Leopard that allow you to access frequently used files directly from the Dock. Dragging a folder to the right side of the Dock creates a stack. Stacks can be viewed as a fan or grid and allow easy access and organization of files. Customization options exist for sorting and viewing stacks.
Stacks are a new feature in Mac OS X Leopard that allow you to access frequently used files directly from the Dock. Stacks can be created by dragging any folder to the right side of the Dock. Clicking a stack will display its contents in either a fan or grid layout. Files can be added or removed from stacks by dragging them in or out. The Documents and Downloads stacks are pre-made for organizing common file types.
Stacks are a new feature in Mac OS X Leopard that allow you to access frequently used files directly from the Dock. Dragging a folder to the right side of the Dock creates a stack. Stacks can be viewed as a fan or grid and allow easy access and organization of files. Customization options exist for sorting and viewing stacks.
Stacks are a new feature in Mac OS X Leopard that allow you to access frequently used files directly from the Dock. Dragging a folder to the right side of the Dock creates a stack. Stacks can be viewed as a fan or grid and allow easy access and organization of files. Customization options exist for sorting and viewing stacks.
Stacks are a new feature in Mac OS X Leopard that allow you to access frequently used files directly from the Dock. Stacks can be created by dragging any folder to the right side of the Dock. Clicking a stack will display its contents in either a fan or grid layout. Files can be added or removed from stacks by dragging them in or out. The Documents and Downloads stacks are pre-made for organizing common file types.
Stacks are a new feature in Mac OS X Leopard that allow you to access frequently used files directly from the Dock. Dragging a folder to the right side of the Dock creates a stack. Stacks can be viewed as a fan or grid and allow easy access and organization of files. Customization options exist for sorting and viewing stacks.
Stacks are a new feature in Mac OS X Leopard that allow you to access frequently used files directly from the Dock. Dragging a folder to the right side of the Dock creates a stack. Stacks can be viewed as a fan or grid and allow easy access and organization of files. Customization options exist for sorting and viewing stacks.
Stacks are a new feature in Mac OS X Leopard that allow you to access frequently used files directly from the Dock. Dragging a folder to the right side of the Dock creates a stack. Stacks can be viewed as a fan or grid and allow easy access and organization of files. Customization options exist for sorting and viewing stacks.
The document discusses key concepts in distributed systems including networking, remote procedure calls (RPC), and transaction processing systems (TPS). It covers networking fundamentals like sockets and ports. It describes how RPC works by allowing functions to be called remotely. It explains the ACID properties that TPS must support for atomicity, consistency, isolation, and durability of transactions processed across distributed systems.
Introduction & Parellelization on large scale clustersSri Prasanna
This document provides an overview of distributed computing and parallelization challenges. It discusses how parallelization can be difficult due to synchronization issues when multiple threads access shared resources. Various synchronization primitives are introduced like semaphores, condition variables, and barriers to help coordinate parallel threads. The challenges of deadlocks are also covered. MapReduce is then introduced as a paradigm that handles data distribution and synchronization challenges for distributed computing problems.
This document provides an overview of MapReduce theory and implementation:
- MapReduce is a programming model that allows for automatic parallelization and distribution of large-scale data processing across hundreds/thousands of CPUs.
- It borrows concepts from functional programming, requiring users to implement map and reduce functions. Map processes key-value pairs in parallel while reduce combines intermediate outputs.
- The MapReduce framework handles fault tolerance, locality of data and tasks, and other optimizations to make large data processing efficient and scalable.
This document discusses several distributed computing systems:
1) DNS is a distributed system that maps domain names to IP addresses using a hierarchical naming structure and caching DNS servers for efficiency.
2) BOINC is a volunteer computing platform that uses over a million computers worldwide for distributed applications like disease research. It provides incentives and verifies results to prevent cheating.
3) PlanetLab is a research network with over 700 servers globally that allows testing new distributed systems at large scales under realistic conditions. It isolates projects using virtualization and trust relationships.
Temple of Asclepius in Thrace. Excavation resultsKrassimira Luka
The temple and the sanctuary around were dedicated to Asklepios Zmidrenus. This name has been known since 1875 when an inscription dedicated to him was discovered in Rome. The inscription is dated in 227 AD and was left by soldiers originating from the city of Philippopolis (modern Plovdiv).
A Visual Guide to 1 Samuel | A Tale of Two HeartsSteve Thomason
These slides walk through the story of 1 Samuel. Samuel is the last judge of Israel. The people reject God and want a king. Saul is anointed as the first king, but he is not a good king. David, the shepherd boy is anointed and Saul is envious of him. David shows honor while Saul continues to self destruct.
How to Manage Reception Report in Odoo 17Celine George
A business may deal with both sales and purchases occasionally. They buy things from vendors and then sell them to their customers. Such dealings can be confusing at times. Because multiple clients may inquire about the same product at the same time, after purchasing those products, customers must be assigned to them. Odoo has a tool called Reception Report that can be used to complete this assignment. By enabling this, a reception report comes automatically after confirming a receipt, from which we can assign products to orders.
Gender and Mental Health - Counselling and Family Therapy Applications and In...PsychoTech Services
A proprietary approach developed by bringing together the best of learning theories from Psychology, design principles from the world of visualization, and pedagogical methods from over a decade of training experience, that enables you to: Learn better, faster!
Elevate Your Nonprofit's Online Presence_ A Guide to Effective SEO Strategies...TechSoup
Whether you're new to SEO or looking to refine your existing strategies, this webinar will provide you with actionable insights and practical tips to elevate your nonprofit's online presence.
How to Setup Default Value for a Field in Odoo 17Celine George
In Odoo, we can set a default value for a field during the creation of a record for a model. We have many methods in odoo for setting a default value to the field.
2. Sorting problem
Ex. Student record in a University.
Sort. Rearrange array of N objects into ascending order.
2
3. Sample sort client
Goal. Sort any type of data.
Ex 1. Sort random numbers in ascending order.
public class Experiment % java Experiment 10
{ 0.08614716385210452
public static void main(String[] args) 0.09054270895414829
0.10708746304898642
{
0.21166190071646818
int N = Integer.parseInt(args[0]); 0.363292849257276
Double[] a = new Double[N]; 0.460954145685913
for (int i = 0; i < N; i++) 0.5340026311350087
a[i] = StdRandom.uniform(); 0.7216129793703496
Insertion.sort(a); 0.9003500354411443
0.9293994908845686
for (int i = 0; i < N; i++)
StdOut.println(a[i]);
}
}
3
4. Sample sort client
Goal. Sort any type of data.
Ex 2. Sort strings from standard input in alphabetical order.
public class StringSort
{
public static void main(String[] args)
{
String[] a = StdIn.readAll().split("s+");
Insertion.sort(a);
for (int i = 0; i < N; i++)
StdOut.println(a[i]);
}
}
% more words3.txt
bed bug dad dot zoo ... all bad bin
% java StringSort < words.txt
all bad bed bug dad ... yes yet zoo
4
5. Sample sort client
Goal. Sort any type of data.
Ex 3. Sort the files in a given directory by filename.
import java.io.File; % java Files .
public class Files Insertion.class
{ Insertion.java
InsertionX.class
public static void main(String[] args)
InsertionX.java
{ Selection.class
File directory = new File(args[0]); Selection.java
File[] files = directory.listFiles(); Shell.class
Insertion.sort(files); Shell.java
for (int i = 0; i < files.length; i++) ShellX.class
ShellX.java
StdOut.println(files[i]);
}
}
5
6. Callbacks
Goal. Sort any type of data.
Q. How can sort know to compare data of type String, Double, and File
without any information about the type of an item?
Callbacks.
• Client passes array of objects to sorting routine.
• Sorting routine calls back object's compare function as needed.
Implementing callbacks.
• Java: interfaces.
• C: function pointers.
• C++: class-type functors.
• ML: first-class functions and functors.
6
7. Callbacks: roadmap
client object implementation
import java.io.File; public class File
public class SortFiles implements Comparable<File>
{ {
public static void main(String[] args) ...
{ public int compareTo(File b)
File directory = new File(args[0]); {
File[] files = directory.listFiles(); ...
Insertion.sort(files); return -1;
for (int i = 0; i < files.length; i++) ...
StdOut.println(files[i]); return +1;
} ...
} return 0;
}
}
built in to Java
interface
public interface Comparable<Item> sort implementation
{ public static void sort(Comparable[] a)
public int compareTo(Item); {
} int N = a.length;
for (int i = 0; i < N; i++)
for (int j = i; j > 0; j--)
if (a[j].compareTo(a[j-1]))
exch(a, j, j-1);
else break;
Key point: no reference to File
}
7
8. Comparable interface API
Comparable interface. Implement compareTo() so that v.compareTo(w):
• Returns a negative integer if v is less than w.
• Returns a positive integer if v is greater than w.
• Returns zero if v is equal to w.
public interface Comparable<Item>
{
public int compareTo(Item that);
}
Consistency. Implementation must ensure a total order.
• Transitivity: if (a < b) and (b < c), then (a < c).
• Trichotomy: either (a < b) or (b < a) or (a = b).
Built-in comparable types. String, Double, Integer, Date, File, ...
User-defined comparable types. Implement the Comparable interface.
8
9. Implementing the Comparable interface: example 1
Date data type. Simplified version of java.util.Date.
public class Date implements Comparable<Date>
{
private final int month, day, year;
public Date(int m, int d, int y)
{
only compare dates
month = m; to other dates
day = d;
year = y;
}
public int compareTo(Date that)
{
if (this.year < that.year ) return -1;
if (this.year > that.year ) return +1;
if (this.month < that.month) return -1;
if (this.month > that.month) return +1;
if (this.day < that.day ) return -1;
if (this.day > that.day ) return +1;
return 0;
}
}
9
10. Implementing the Comparable interface: example 2
Domain names.
• Subdomain: bolle.cs.princeton.edu.
• Reverse subdomain: edu.princeton.cs.bolle.
• Sort by reverse subdomain to group by category.
subdomains
public class Domain implements Comparable<Domain>
{ ee.princeton.edu
private final String[] fields; cs.princeton.edu
private final int N; princeton.edu
cnn.com
public Domain(String name)
google.com
{
apple.com
fields = name.split(".");
N = fields.length; www.cs.princeton.edu
} bolle.cs.princeton.edu
public int compareTo(Domain that)
{ reverse-sorted subdomains
for (int i = 0; i < Math.min(this.N, that.N); i++)
{ com.apple
String s = fields[this.N - i - 1]; com.cnn
String t = fields[that.N - i - 1]; com.google
int cmp = s.compareTo(t);
edu.princeton
if (cmp < 0) return -1;
edu.princeton.cs
else if (cmp > 0) return +1;
}
edu.princeton.cs.bolle
return this.N - that.N; edu.princeton.cs.www
} edu.princeton.ee
}
10
11. Two useful sorting abstractions
Helper functions. Refer to data through compares and exchanges.
Less. Is object v less than w ?
private static boolean less(Comparable v, Comparable w)
{
return v.compareTo(w) < 0;
}
Exchange. Swap object in array a[] at index i with the one at index j.
private static void exch(Comparable[] a, int i, int j)
{
Comparable t = a[i];
a[i] = a[j];
a[j] = t;
}
11
12. Testing
Q. How to test if an array is sorted?
private static boolean isSorted(Comparable[] a)
{
for (int i = 1; i < a.length; i++)
if (less(a[i], a[i-1])) return false;
return true;
}
Q. If the sorting algorithm passes the test, did it correctly sort its input?
A1. Not necessarily!
A2. Yes, if data accessed only through exch() and less().
12
13. ‣ rules of the game
‣ selection sort
‣ insertion sort
‣ sorting challenges
‣ shellsort
13
14. Selection sort
Algorithm. ↑ scans from left to right.
Invariants.
• Elements to the left of ↑ (including ↑) fixed and in ascending order.
• No element to right of ↑ is smaller than any element to its left.
↑
in final order
14
15. Selection sort inner loop
To maintain algorithm invariants:
• Move the pointer to the right.
i++;
in final order ↑
• Identify index of minimum item on right.
int min = i;
for (int j = i+1; j < N; j++)
if (less(a[j], a[min]))
in final order ↑ ↑
min = j;
• Exchange into position.
exch(a, i, min);
in final order ↑ ↑
15
16. Selection sort: Java implementation
public class Selection {
public static void sort(Comparable[] a)
{
int N = a.length;
for (int i = 0; i < N; i++)
{
int min = i;
for (int j = i+1; j < N; j++)
if (less(a[j], a[min]))
min = j;
exch(a, i, min);
}
}
private boolean less(Comparable v, Comparable w)
{ /* as before */ }
private boolean exch(Comparable[] a, int i, int j)
{ /* as before */ }
}
16
17. Selection sort: mathematical analysis
Proposition A. Selection sort uses (N-1) + (N-2) + ... + 1 + 0 ~ N2/2
compares and N exchanges.
a[]
entries in black
i min 0 1 2 3 4 5 6 7 8 9 10 are examined to find
the minimum
S O R T E X A M P L E
0 6 S O R T E X A M P L E
entries in red
1 4 A O R T E X S M P L E are a[min]
2 10 A E R T O X S M P L E
3 9 A E E T O X S M P L R
4 7 A E E L O X S M P T R
5 7 A E E L M X S O P T R
6 8 A E E L M O S X P T R
7 10 A E E L M O P X S T R
8 8 A E E L M O P R S T X
entries in gray are
9 9 A E E L M O P R S T X in final position
10 10 A E E L M O P R S T X
A E E L M O P R S T X
Trace of selection sort (array contents just after each exchange)
Running time insensitive to input. Quadratic time, even if array is presorted.
Data movement is minimal. Linear number of exchanges.
17
18. ‣ rules of the game
‣ selection sort
‣ insertion sort
‣ sorting challenges
‣ shellsort
18
19. Insertion sort
Algorithm. ↑ scans from left to right.
Invariants.
• Elements to the left of ↑ (including ↑) are in ascending order.
• Elements to the right of ↑ have not yet been seen.
in order ↑ not yet seen
19
20. Insertion sort inner loop
To maintain algorithm invariants:
• Move the pointer to the right.
i++;
↑
in order not yet seen
• Moving from right to left, exchange
a[i] with each larger element to its left.
for (int j = i; j > 0; j--)
if (less(a[j], a[j-1]))
exch(a, j, j-1);
else break; ↑ ↑ ↑↑
in order not yet seen
20
21. Insertion sort: Java implementation
public class Insertion {
public static void sort(Comparable[] a)
{
int N = a.length;
for (int i = 0; i < N; i++)
for (int j = i; j > 0; j--)
if (less(a[j], a[j-1]))
exch(a, j, j-1);
else break;
}
private boolean less(Comparable v, Comparable w)
{ /* as before */ }
private boolean exch(Comparable[] a, int i, int j)
{ /* as before */ }
}
21
22. Insertion sort: mathematical analysis
Proposition B. For randomly-ordered data with distinct keys, insertion sort
uses ~ N2/4 compares and N2/4 exchanges on the average.
Pf. For randomly data, we expect each element to move halfway back.
a[]
i j 0 1 2 3 4 5 6 7 8 9 10
S O R T E X A M P L E entries in gray
do not move
1 0 O S R T E X A M P L E
2 1 O R S T E X A M P L E
3 3 O R S T E X A M P L E
4 0 E O R S T X A M P L E entry in red
is a[j]
5 5 E O R S T X A M P L E
6 0 A E O R S T X M P L E
7 2 A E M O R S T X P L E
entries in black
8 4 A E M O P R S T X L E moved one position
9 2 A E L M O P R S T X E right for insertion
10 2 A E E L M O P R S T X
A E E L M O P R S T X
Trace of insertion sort (array contents just after each insertion)
22
23. Insertion sort: best and worst case
Best case. If the input is in ascending order, insertion sort makes
N-1 compares and 0 exchanges.
A E E L M O P R S T X
Worst case. If the input is in descending order (and no duplicates),
insertion sort makes ~ N2/2 compares and ~ N2/2 exchanges.
X T S R P O M L E E A
23
24. Insertion sort: partially sorted inputs
Def. An inversion is a pair of keys that are out of order.
A E E L M O T R X P S
T-R T-P T-S X-P X-S
(5 inversions)
Def. An array is partially sorted if the number of inversions is O(N).
• Ex 1. A small array appended to a large sorted array.
• Ex 2. An array with only a few elements out of place.
Proposition C. For partially-sorted arrays, insertion sort runs in linear time.
Pf. Number of exchanges equals the number of inversions.
number of compares = exchanges + (N-1)
24
25. ‣ rules of the game
‣ selection sort
‣ insertion sort
‣ sorting challenges
‣ shellsort
25
26. Rather than tracing the progress of a sort with key values such as letters, numbers or
Sorting challenge 0
words, we use vertical bars, to be sorted by their heights. As you will see, the advantage
of such a representation is that it can give insights into
the behavior of a sorting method.
Input. Array of doubles.
For example, you can see at a glance on the vi-
sual traces at rightproportional to length.not touch
Plot. Data that insertion sort does
entries to the right of the scan pointer and selection
sort does not touch entries to the left of the scan point- gray entries
Name the clear from the visual traces that, since
sorting method.
are untouched
er. Moreover, it is
• Insertion sort.
insertion sort also does not touch entries smaller than
• Selection sort.
the inserted element, it uses about half the number of
compares as selection sort, on the average.
With our StdDraw library, developing a visual
trace is not much more difficult than doing a standard
trace. We sort Double values, instrument the algorithm
to call show() as appropriate (just as we do for a stan-
dard trace) and develop a version of show() that uses
StdDraw to draw the bars instead of printing the results.
The most complicated task is setting the scale for the y
axis so that the lines of the trace appear in the expected black entries
order. You are encouraged to work EXERCISE 3.1.19 in are involved
in compares
order to gain a better appreciation of the value of visual
traces and the ease of creating them.
An even simpler task is to animate the trace
so that you can see the array dynamically evolve to the
sorted result. Developing an animated trace involves
essentially the same process described in the previous insertion sort selection sort
26
27. Sorting challenge 1
Problem. Sort a file of huge records with tiny keys.
Ex. Reorganize your MP3 files.
Which sorting method to use?
• System sort.
• Insertion sort.
• Selection sort.
27
28. Sorting challenge 1
Problem. Sort a file of huge records with tiny keys.
Ex. Reorganize your MP3 files.
Which sorting method to use?
• System sort. probably no, selection sort simpler and faster
• Insertion sort. no, too many exchanges
• Selection sort. yes, linear time under reasonable assumptions
Ex: 5,000 records, each 2 million bytes with 100-byte keys.
Cost of comparisons: 100 × 50002 / 2 = 1.25 billion.
Cost of exchanges: 2,000,000 × 5,000 = 10 trillion.
System sort might be a factor of log (5000) slower.
28
29. Sorting challenge 2
Problem. Sort a huge randomly-ordered file of small records.
Ex. Process transaction records for a phone company.
Which sorting method to use?
• System sort.
• Insertion sort.
• Selection sort.
29
30. Sorting challenge 2
Problem. Sort a huge randomly-ordered file of small records.
Ex. Process transaction records for a phone company.
Which sorting method to use?
• System sort. yes, it's designed for this problem
• Insertion sort. no, quadratic time for randomly ordered files
• Selection sort. no, always quadratic time
30
31. Sorting challenge 3
Problem. Sort a huge number of tiny files (each file is independent)
Ex. Daily customer transaction records.
Which sorting method to use?
• System sort.
• Insertion sort.
• Selection sort.
31
32. Sorting challenge 3
Problem. Sort a huge number of tiny files (each file is independent)
Ex. Daily customer transaction records.
Which sorting method to use?
• System sort. no, too much overhead
• Insertion sort. yes, less overhead than system sort
• Selection sort. yes, less overhead than system sort
Ex: 4 record file.
4 N log N + 35 = 70
2N2 = 32
32
33. Sorting challenge 4
Problem. Sort a huge file that is already almost in order.
Ex. Resort a huge database after a few changes.
Which sorting method to use?
• System sort.
• Insertion sort.
• Selection sort.
33
34. Sorting challenge 4
Problem. Sort a huge file that is already almost in order.
Ex. Resort a huge database after a few changes.
Which sorting method to use?
• System sort. no, insertion sort simpler and faster
• Insertion sort. yes, linear time for most definitions of "in order"
• Selection sort. no, always takes quadratic time
Ex.
• A B C D E F H I J G P K L M N O Q R S T U V W X Y Z
• Z A B C D E F G H I J K L M N O P Q R S T U V W X Y
34
35. ‣ rules of the game
‣ selection sort
‣ insertion sort
‣ animations
‣ shellsort
35
36. Insertion sort animation
left of pointer is in sorted order right of pointer is untouched
a[i]
i
36
39. move through the array only one place at a time. For exa
Shellsort overview smallest key happens to be at the end of the array, N steps are
ment where it belongs. Shellsort is a simple extension of ins
by allowing exchanges of elements that are far apart, to pro
Idea. Move elements more than one position at a time by h-sorting the file.
that can be efficiently sorted, eventually by insertion sort.
The idea is to rearrange the array to give it the pro
a 3-sorted file is 3 interleaved sorted files element (starting anywhere)
h=3 Such an array is said to be h-s
A E L E O P M S X R T h-sorted array is h independen
A E M R terleaved together. By h-sorting
E O S T we can move elements in the ar
L P X make it easier to h-sort for sma
a procedure for any increment
h=7
ends in 1 will produce a sorted
M O L E E X A S P R T
One way to impleme
Shellsort. h-sort the M file for a decreasing S sequence of values of to use insertion sort
each h, h.
E P the h subsequences. Despite
L R
this process, we can use an ev
E T
input S O R T E X A M P L E cisely because the subsequenc
E
7-sort M O L E E X A S P R T
L
h-sorting the array, we simply
3-sort A E L E O P M S X R T A
the previous elements in its
larger elements to the right. W
An h-sorted file is h M O P R sorted files using the insertion-sort code,
1-sort A E E L interleaved S T X
Shellsort trace (array contents after each pass) or decrement by h instead of 1
array. This observation reduces the shellsort implementatio
38
40. h-sorting
How to h-sort a file? Insertion sort, with stride length h.
3-sorting a file
M O L E E X A S P R T
E O L M E X A S P R T
E E L M O X A S P R T
E E L M O X A S P R T
A E L E O X M S P R T
A E L E O X M S P R T
A E L E O P M S X R T
A E L E O P M S X R T
A E L E O P M S X R T
A E L E O P M S X R T
Why insertion sort?
• Big increments ⇒ small subfiles.
• Small increments ⇒ nearly in order. [stay tuned]
39
41. Shellsort example
input 1-sort
S O R T E X A M P L E A E L E O P M S X R T
A E L E O P M S X R T
A E L E O P M S X R T
7-sort A E E L O P M S X R T
S O R T E X A M P L E A E E L O P M S X R T
M O R T E X A S P L E A E E L O P M S X R T
M O R T E X A S P L E A E E L M O P S X R T
M O L T E X A S P R E A E E L M O P S X R T
M O L E E X A S P R T A E E L M O P S X R T
A E E L M O P R S X T
A E E L M O P R S T X
3-sort
M O L E E X A S P R T
E O L M E X A S P R T
E E L M O X A S P R T result
E E L M O X A S P R T A E E L M O P R S T X
A E L E O X M S P R T
A E L E O X M S P R T
A E L E O P M S X R T
A E L E O P M S X R T
A E L E O P M S X R T
40
42. Shellsort: Java implementation
public class Shell
{
public static void sort(Comparable[] a)
{
int N = a.length;
int[] incs = { 1391376, 463792, 198768, 86961,
33936, 13776, 4592, 1968, 861, magic increment
336, 112, 48, 21, 7, 3, 1 sequence
};
for (int k = 0; k < incs.length; k++)
{
int h = incs[k];
for (int i = h; i < N; i++)
for (int j = i; j >= h; j-= h)
if (less(a[j], a[j-h])) insertion sort
exch(a, j, j-h);
else break;
}
}
private boolean less(Comparable v, Comparable w)
{ /* as before */ }
private boolean exch(Comparable[] a, int i, int j)
{ /* as before */ }
}
41
43. Visual trace of shellsort
input
112-sorted
48-sorted
21-sorted
7-sorted
3-sorted
result
42
47. Empirical analysis of shellsort
Property. The number of compares used by shellsort with the increments 1, 4,
13, 40, ... is at most by a small multiple of N times the # of increments used.
N comparisons N1.289 2.5 N lg N
5,000 93 58 106
10,000 209 143 230
20,000 467 349 495
40,000 1022 855 1059
80,000 2266 2089 2257
measured in thousands
Remark. Accurate model has not yet been discovered (!)
45
48. Shellsort: mathematical analysis
Proposition. A g-sorted array remains g-sorted after h-sorting it.
Pf. Harder than you'd think!
7-sort 3-sort
M O R T E X A S P L E M O L E E X A S P R T
M O R T E X A S P L E E O L M E X A S P R T
M O L T E X A S P R E E E L M O X A S P R T
M O L E E X A S P R T E E L M O X A S P R T
M O L E E X A S P R T A E L E O X M S P R T
A E L E O X M S P R T
A E L E O P M S X R T
A E L E O P M S X R T
A E L E O P M S X R T
A E L E O P M S X R T
still 7-sorted
Proposition. The worst-case number of compares for shellsort using
the 3x+1 increment sequence 1, 4, 13, 40, 121, 364, … is O(N3/2).
46
49. Why are we interested in shellsort?
Example of simple idea leading to substantial performance gains.
Useful in practice.
• Fast unless file size is huge.
• Tiny, fixed footprint for code (used in embedded systems).
• Hardware sort prototype.
Simple algorithm, nontrivial performance, interesting questions
• Asymptotic growth rate?
• Best sequence of increments?
• Average case performance? open problem: find a better increment sequence
Lesson. Some good algorithms are still waiting discovery.
47
Editor's Notes
Plus. Code reuse for all types of data.
Minus. Significant overhead in inner loop.
This course.
Enables focus on algorithm implementation.
Use same code for experiments, real-world data.
details for bored
safe to this.N - that.N since both are nonnegative
A1: the sorting algorithm could change the entries in a[], e.g., all to the same value. Then it would surely pass the isSorted() test.
assumes we're sorting real numbers
two helper functions
trucks parked at waiting station, leave in order of timestamp -> expensive exchange, easy compare
array contents just after each exchange
assumes we're sorting real numbers
array contents just after each insertion
insertion sort (left)
selection sort (right)
Note: picture only intended for terminology, not to be consistent with sizes in problem
ok, in reality system sort might just cutoff to insertion sort for small N
red = element to move right into position, with stride length 3
Invented by D. L. Shell in 1959, hence its name
A. Insertion sort is the method of choice for big and small increments!