Searching is a process to find a value with specified properties among a collection of items. Linear searching compares each item sequentially until a match is found, taking O(n) time. Binary searching requires a sorted list and compares the middle item first, dividing the search space in half with each comparison, taking O(log n) time on average. Sorting rearranges items in ascending or descending order using algorithms like bubble, insertion, selection, quick, and merge sort that differ in efficiency and memory requirements.
Searching techniques involve finding a value with specified properties within a collection. Linear searching compares each item sequentially until a match is found, taking O(n) time. Binary searching requires a sorted list and compares the middle item first, reducing the search space by half with each comparison, taking O(log n) time on average. Sorting rearranges elements in ascending or descending order using techniques like bubble, insertion, and selection sort that have O(n^2) worst-case time and quicksort that has an average case of O(n log n) time.
This document describes stochastic definite clause grammars (SDCG), which extend definite clause grammars (DCG) with probabilities. SDCG transforms a DCG into a stochastic logic program using PRISM, allowing probabilistic inferences and parameter learning. The probabilistic model assigns a random variable to each rule expansion. SDCG introduces syntax extensions like regular expressions and macros to make grammars more concise. Conditioned rules allow modeling higher-order hidden Markov models by selecting rules based on variable unification. SDCG provides tools for parsing sentences and learning rule probabilities from data.
The document discusses Java methods. It defines a method as a collection of statements grouped to perform an operation. A method signature combines the method name and parameter list. Formal parameters are defined in the method header, while actual parameters are the values passed when invoking the method. The document provides an example method that returns the maximum of two integers.
This document provides an overview of various Java programming concepts including methods, command line arguments, constructors, this keyword, super keyword, static keyword, final keyword, and finally block. It discusses how to define methods with and without return values, pass parameters, and overload methods. It explains how to pass command line arguments to the main method. It describes the different types of constructors and how to use this and super keywords. It discusses how to declare static variables, methods, blocks, and nested classes. It also explains how to use the final keyword to create constant variables.
This document provides a summary of key Java concepts including primitive data types, arrays, classes, methods, variables, operators, comments, wrapper classes, class member accessibility, access modifiers, arrays, the null value, classes, methods, variables, operators, comments, flow control statements, program structure, keywords, operator precedence, scanner class methods, converting strings to numbers, event listeners, swing components, JComboBox methods, and Java packages. It also includes examples of various Java concepts.
This document discusses pointers and arrays in C programming. It begins by explaining that an array stores multiple elements of the same type in contiguous memory locations, while a pointer variable stores the address of another variable. It then provides examples of how to declare and initialize arrays and pointers, pass arrays to functions, and perform operations like pointer arithmetic on arrays using pointers. The key advantages of arrays like storing multiple values and accessing elements using indexes are also summarized.
This document discusses pointers and arrays in C programming. It begins by explaining that an array stores multiple elements of the same type in contiguous memory locations, while a pointer variable stores the address of another variable. It then provides examples of how to declare and initialize arrays and pointers, pass arrays to functions, and perform operations like pointer arithmetic on arrays using pointers. The key advantages of arrays like storing multiple values and accessing elements using indexes are also summarized.
Searching techniques involve finding a value with specified properties within a collection. Linear searching compares each item sequentially until a match is found, taking O(n) time. Binary searching requires a sorted list and compares the middle item first, reducing the search space by half with each comparison, taking O(log n) time on average. Sorting rearranges elements in ascending or descending order using techniques like bubble, insertion, and selection sort that have O(n^2) worst-case time and quicksort that has an average case of O(n log n) time.
This document describes stochastic definite clause grammars (SDCG), which extend definite clause grammars (DCG) with probabilities. SDCG transforms a DCG into a stochastic logic program using PRISM, allowing probabilistic inferences and parameter learning. The probabilistic model assigns a random variable to each rule expansion. SDCG introduces syntax extensions like regular expressions and macros to make grammars more concise. Conditioned rules allow modeling higher-order hidden Markov models by selecting rules based on variable unification. SDCG provides tools for parsing sentences and learning rule probabilities from data.
The document discusses Java methods. It defines a method as a collection of statements grouped to perform an operation. A method signature combines the method name and parameter list. Formal parameters are defined in the method header, while actual parameters are the values passed when invoking the method. The document provides an example method that returns the maximum of two integers.
This document provides an overview of various Java programming concepts including methods, command line arguments, constructors, this keyword, super keyword, static keyword, final keyword, and finally block. It discusses how to define methods with and without return values, pass parameters, and overload methods. It explains how to pass command line arguments to the main method. It describes the different types of constructors and how to use this and super keywords. It discusses how to declare static variables, methods, blocks, and nested classes. It also explains how to use the final keyword to create constant variables.
This document provides a summary of key Java concepts including primitive data types, arrays, classes, methods, variables, operators, comments, wrapper classes, class member accessibility, access modifiers, arrays, the null value, classes, methods, variables, operators, comments, flow control statements, program structure, keywords, operator precedence, scanner class methods, converting strings to numbers, event listeners, swing components, JComboBox methods, and Java packages. It also includes examples of various Java concepts.
This document discusses pointers and arrays in C programming. It begins by explaining that an array stores multiple elements of the same type in contiguous memory locations, while a pointer variable stores the address of another variable. It then provides examples of how to declare and initialize arrays and pointers, pass arrays to functions, and perform operations like pointer arithmetic on arrays using pointers. The key advantages of arrays like storing multiple values and accessing elements using indexes are also summarized.
This document discusses pointers and arrays in C programming. It begins by explaining that an array stores multiple elements of the same type in contiguous memory locations, while a pointer variable stores the address of another variable. It then provides examples of how to declare and initialize arrays and pointers, pass arrays to functions, and perform operations like pointer arithmetic on arrays using pointers. The key advantages of arrays like storing multiple values and accessing elements using indexes are also summarized.
This document introduces the concept of logic monads in Scala by explaining logic programming with Prolog and how it can be implemented using monads and unification. It covers logic programming concepts like backtracking and unification, and how they can be modeled in Scala using monads. It then explains how to implement a logic monad in Scala using the State monad and List monad. Finally, it shows an example implementation of the Prolog predicate my_append in the logic monad.
Introduction to ad-3.4, an automatic differentiation library in Haskellnebuta
This document provides an introduction to the ad-3.4 automatic differentiation library in Haskell. It summarizes the key capabilities of the library including differentiating arbitrary mathematical functions, calculating gradients, Jacobians and Hessians. It also provides examples of how to use the library to differentiate single variable scalar functions, calculate gradients, perform Taylor expansions, and check equality of functions. The document discusses some of the core classes and types in the library like Mode, Lifted and AD that enable automatic differentiation. It points to resources that explain the mechanism of automatic differentiation and package structure.
The document discusses the theory of automata and formal languages including:
- Different types of automata like finite automata, pushdown automata, and Turing machines.
- Context-free grammars and properties of regular, context-free, and recursively enumerable languages.
- Operations on strings and languages like concatenation, Kleene closure, and positive closure.
- Proofs techniques like proof by induction and proof by contradiction.
Learning with classification and clustering, neural networksShaun D'Souza
This document discusses various machine learning techniques including supervised learning methods like classification and regression as well as unsupervised learning methods like text clustering. It provides examples of applying classification to iris flower data and sentiment analysis using naive Bayes. It also discusses natural language processing tasks like part-of-speech tagging, chunking, parsing and named entity recognition and how these can be applied using tools like OpenNLP. Finally, it briefly covers document clustering and how it is used to group unlabeled documents in an unsupervised manner.
The document discusses theory of automata and formal languages including different types of automata like finite automata, pushdown automata, and Turing machines. It covers topics like regular expressions, context-free grammars, recursively enumerable languages, and proofs by induction and contradiction. The document provides references for further reading and outlines the syllabus covering these foundational concepts in theory of computation.
This document discusses chapters and concepts from Liang's Introduction to Java Programming textbook. It covers defining and using methods in Java, including defining methods with parameters and return types, invoking methods by passing arguments, and how method calls are handled by the call stack. Key points covered include formal vs actual parameters, method signatures, return values, and reusing methods from other classes. Examples are provided to demonstrate calculating sums and finding maximum values using methods.
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.
This document discusses three functional patterns: continuations, format combinators, and nested data types. It provides examples of each pattern in Scala. Continuations are represented using explicit continuation-passing style and delimited control operators. Format combinators represent formatted output as typed combinators rather than untyped strings. Nested data types generalize recursive data types to allow the type parameter of recursive invocations to differ, as in square matrices represented as a nested data type. The document concludes by drawing an analogy between fast exponentiation and representing square matrices as a nested data type.
This document provides an overview of various data structures available in the PHP Standard Library (SPL). It discusses DoublyLinkedList, Stack, Queue, Heap, MaxHeap, MinHeap, PriorityQueue, FixedArray, and ObjectStorage. For each data structure, it describes their implementation and time complexity for common operations like insertion, deletion, lookup, etc. The document aims to help understand which data structure to use for different use cases based on their performance characteristics.
RuleML2015 : Hybrid Relational and Graph Reasoning Mark Proctor
The document discusses building a hybrid reactive rule engine that can handle both relational and graph-based reasoning. It proposes introducing a new "from" keyword and FromNode to allow rules to access nested objects and their references. The FromNode evaluates an expression on a tuple to retrieve an object or collection, then propagates a new tuple to its child node for each object returned, enabling traversal of graph structures within rules. This addresses requirements for accessing child objects and their relations via a reactive mechanism.
TI1220 Lecture 8: Traits & Type ParameterizationEelco Visser
Traits allow code reuse through mixing in. Traits can contain fields, methods, and act as types. When mixed into classes, traits are linearly ordered and calls to super are dispatched accordingly. This avoids problems with multiple inheritance by ensuring there is always a single linearization of supertypes. The example code defines classes and traits for animals with traits for properties like being furry or having legs. It demonstrates how trait mixing and method overriding works.
ppt of class and methods in java,recursion in java,nested class,java,command line argument,method overloading,call by value,call by reference,constructor overloading core java ppt
This document summarizes Chapter 6 of Liang's Introduction to Java Programming, Ninth Edition. It introduces arrays as a data structure that represents a collection of the same type of data. It describes how to declare array variables, create arrays, initialize arrays, access array elements using indexes, and use array initializers. It also provides examples of common array operations and how to trace a sample program that uses arrays.
Templates allow functions and classes to operate on generic types in C++. There are two types of templates: class templates and function templates. Function templates are functions that can operate on generic types, allowing code to be reused for multiple types without rewriting. Template parameters allow types to be passed to templates, similar to how regular parameters pass values. When a class, function or static member is generated from a template, it is called template instantiation.
Inspired by Josh Bloch's Java Puzzlers, we put together our own Python Puzzlers. This slide deck brings you a set of 10 python puzzlers, that are fun and educational. Each puzzler will show you a piece of python code. Your task if to figure out what happens when the code is run. Whether you're a python beginner or a passionate python veteran, we hope that there's something to learn for everybody.
This slide deck was first presented at shopkick. Nandan Sawant and Ryan Rueth are engineers at shopkick. Keeping the audience in mind, most of the puzzlers are based on python 2.x.
A presentation about the ideas of recursion and recursive functions.
This is my lecture presentation during A. Paruj Ratanaworabhan’s basic preparatory programming course for freshmen: Introduction to Programming: A Tutorial for New Comers Using Python
This document contains the solutions to 8 questions related to Java OOP concepts such as inheritance, polymorphism, method overriding and overloading.
The questions cover topics like determining the output of sample code, identifying true/false statements about OOP concepts, explaining the differences between method overriding and overloading, designing UML class diagrams to model relationships between classes, and writing Java programs to test class hierarchies and subclasses.
Detailed explanations and code samples are provided for each question to demonstrate concepts like invoking superclass constructors, determining pass/fail conditions for student grades based on average test scores, implementing abstract classes and interfaces, and creating subclasses that extend the functionality of base classes.
Lecture 8 abstract class and interfacemanish kumar
The document discusses abstract classes and interfaces in Java. It provides examples of abstract classes with abstract and non-abstract methods, and how abstract classes can be extended. It also discusses interfaces and how they can be implemented, allow for multiple inheritance, and define marker interfaces. The key differences between abstract classes and interfaces are that abstract classes can include non-abstract methods while interfaces contain only abstract methods, and abstract classes allow single inheritance while interfaces allow multiple inheritance.
The document discusses various searching and sorting techniques. It describes linear and binary searching algorithms. It also explains different sorting algorithms like bubble sort, insertion sort, selection sort, and quick sort. Their time complexities and applications are discussed.
This document discusses various sorting and searching algorithms. It begins by listing sorting algorithms like selection sort, insertion sort, bubble sort, merge sort, and radix sort. It then discusses searching algorithms like linear/sequential search and binary search. It provides details on the implementation and time complexity of linear search, binary search, bubble sort, insertion sort, selection sort, and merge sort. Key points covered include the divide and conquer approach of merge sort and how binary search recursively halves the search space.
This document introduces the concept of logic monads in Scala by explaining logic programming with Prolog and how it can be implemented using monads and unification. It covers logic programming concepts like backtracking and unification, and how they can be modeled in Scala using monads. It then explains how to implement a logic monad in Scala using the State monad and List monad. Finally, it shows an example implementation of the Prolog predicate my_append in the logic monad.
Introduction to ad-3.4, an automatic differentiation library in Haskellnebuta
This document provides an introduction to the ad-3.4 automatic differentiation library in Haskell. It summarizes the key capabilities of the library including differentiating arbitrary mathematical functions, calculating gradients, Jacobians and Hessians. It also provides examples of how to use the library to differentiate single variable scalar functions, calculate gradients, perform Taylor expansions, and check equality of functions. The document discusses some of the core classes and types in the library like Mode, Lifted and AD that enable automatic differentiation. It points to resources that explain the mechanism of automatic differentiation and package structure.
The document discusses the theory of automata and formal languages including:
- Different types of automata like finite automata, pushdown automata, and Turing machines.
- Context-free grammars and properties of regular, context-free, and recursively enumerable languages.
- Operations on strings and languages like concatenation, Kleene closure, and positive closure.
- Proofs techniques like proof by induction and proof by contradiction.
Learning with classification and clustering, neural networksShaun D'Souza
This document discusses various machine learning techniques including supervised learning methods like classification and regression as well as unsupervised learning methods like text clustering. It provides examples of applying classification to iris flower data and sentiment analysis using naive Bayes. It also discusses natural language processing tasks like part-of-speech tagging, chunking, parsing and named entity recognition and how these can be applied using tools like OpenNLP. Finally, it briefly covers document clustering and how it is used to group unlabeled documents in an unsupervised manner.
The document discusses theory of automata and formal languages including different types of automata like finite automata, pushdown automata, and Turing machines. It covers topics like regular expressions, context-free grammars, recursively enumerable languages, and proofs by induction and contradiction. The document provides references for further reading and outlines the syllabus covering these foundational concepts in theory of computation.
This document discusses chapters and concepts from Liang's Introduction to Java Programming textbook. It covers defining and using methods in Java, including defining methods with parameters and return types, invoking methods by passing arguments, and how method calls are handled by the call stack. Key points covered include formal vs actual parameters, method signatures, return values, and reusing methods from other classes. Examples are provided to demonstrate calculating sums and finding maximum values using methods.
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.
This document discusses three functional patterns: continuations, format combinators, and nested data types. It provides examples of each pattern in Scala. Continuations are represented using explicit continuation-passing style and delimited control operators. Format combinators represent formatted output as typed combinators rather than untyped strings. Nested data types generalize recursive data types to allow the type parameter of recursive invocations to differ, as in square matrices represented as a nested data type. The document concludes by drawing an analogy between fast exponentiation and representing square matrices as a nested data type.
This document provides an overview of various data structures available in the PHP Standard Library (SPL). It discusses DoublyLinkedList, Stack, Queue, Heap, MaxHeap, MinHeap, PriorityQueue, FixedArray, and ObjectStorage. For each data structure, it describes their implementation and time complexity for common operations like insertion, deletion, lookup, etc. The document aims to help understand which data structure to use for different use cases based on their performance characteristics.
RuleML2015 : Hybrid Relational and Graph Reasoning Mark Proctor
The document discusses building a hybrid reactive rule engine that can handle both relational and graph-based reasoning. It proposes introducing a new "from" keyword and FromNode to allow rules to access nested objects and their references. The FromNode evaluates an expression on a tuple to retrieve an object or collection, then propagates a new tuple to its child node for each object returned, enabling traversal of graph structures within rules. This addresses requirements for accessing child objects and their relations via a reactive mechanism.
TI1220 Lecture 8: Traits & Type ParameterizationEelco Visser
Traits allow code reuse through mixing in. Traits can contain fields, methods, and act as types. When mixed into classes, traits are linearly ordered and calls to super are dispatched accordingly. This avoids problems with multiple inheritance by ensuring there is always a single linearization of supertypes. The example code defines classes and traits for animals with traits for properties like being furry or having legs. It demonstrates how trait mixing and method overriding works.
ppt of class and methods in java,recursion in java,nested class,java,command line argument,method overloading,call by value,call by reference,constructor overloading core java ppt
This document summarizes Chapter 6 of Liang's Introduction to Java Programming, Ninth Edition. It introduces arrays as a data structure that represents a collection of the same type of data. It describes how to declare array variables, create arrays, initialize arrays, access array elements using indexes, and use array initializers. It also provides examples of common array operations and how to trace a sample program that uses arrays.
Templates allow functions and classes to operate on generic types in C++. There are two types of templates: class templates and function templates. Function templates are functions that can operate on generic types, allowing code to be reused for multiple types without rewriting. Template parameters allow types to be passed to templates, similar to how regular parameters pass values. When a class, function or static member is generated from a template, it is called template instantiation.
Inspired by Josh Bloch's Java Puzzlers, we put together our own Python Puzzlers. This slide deck brings you a set of 10 python puzzlers, that are fun and educational. Each puzzler will show you a piece of python code. Your task if to figure out what happens when the code is run. Whether you're a python beginner or a passionate python veteran, we hope that there's something to learn for everybody.
This slide deck was first presented at shopkick. Nandan Sawant and Ryan Rueth are engineers at shopkick. Keeping the audience in mind, most of the puzzlers are based on python 2.x.
A presentation about the ideas of recursion and recursive functions.
This is my lecture presentation during A. Paruj Ratanaworabhan’s basic preparatory programming course for freshmen: Introduction to Programming: A Tutorial for New Comers Using Python
This document contains the solutions to 8 questions related to Java OOP concepts such as inheritance, polymorphism, method overriding and overloading.
The questions cover topics like determining the output of sample code, identifying true/false statements about OOP concepts, explaining the differences between method overriding and overloading, designing UML class diagrams to model relationships between classes, and writing Java programs to test class hierarchies and subclasses.
Detailed explanations and code samples are provided for each question to demonstrate concepts like invoking superclass constructors, determining pass/fail conditions for student grades based on average test scores, implementing abstract classes and interfaces, and creating subclasses that extend the functionality of base classes.
Lecture 8 abstract class and interfacemanish kumar
The document discusses abstract classes and interfaces in Java. It provides examples of abstract classes with abstract and non-abstract methods, and how abstract classes can be extended. It also discusses interfaces and how they can be implemented, allow for multiple inheritance, and define marker interfaces. The key differences between abstract classes and interfaces are that abstract classes can include non-abstract methods while interfaces contain only abstract methods, and abstract classes allow single inheritance while interfaces allow multiple inheritance.
The document discusses various searching and sorting techniques. It describes linear and binary searching algorithms. It also explains different sorting algorithms like bubble sort, insertion sort, selection sort, and quick sort. Their time complexities and applications are discussed.
This document discusses various sorting and searching algorithms. It begins by listing sorting algorithms like selection sort, insertion sort, bubble sort, merge sort, and radix sort. It then discusses searching algorithms like linear/sequential search and binary search. It provides details on the implementation and time complexity of linear search, binary search, bubble sort, insertion sort, selection sort, and merge sort. Key points covered include the divide and conquer approach of merge sort and how binary search recursively halves the search space.
Arrays allow storing multiple values of the same type. Arrays in C can be declared with the array name, element type, and size. Values can be initialized during or after declaration. Common operations on arrays include sorting, searching, and calculating statistics. Bubble sort iteratively compares and swaps adjacent elements to sort an array in ascending order. Linear search compares each element to a search key, while binary search divides the sorted array in half on each step. Binary search has lower computational complexity of O(log n) compared to O(n) for linear search.
The document discusses linear and binary search algorithms.
Linear search is the simplest algorithm that sequentially compares each element of an array to the target element. It has a worst case time complexity of O(N).
Binary search works on a sorted array by comparing the middle element to the target. It eliminates half of the remaining elements with each comparison. It has a worst case time complexity of O(log n), which is faster than linear search for large data sets.
Pseudocode and C programs are provided as examples to implement linear and binary search.
The document discusses various searching, sorting, and hashing techniques used in data structures and algorithms. It describes linear and binary search methods for finding elements in a list. Linear search has O(n) time complexity while binary search has O(log n) time complexity. Bubble, insertion, and selection sorts are covered as sorting algorithms that arrange elements in ascending or descending order, with bubble sort having O(n^2) time complexity. Hashing techniques like hash functions, separate chaining, and open addressing are also summarized at a high level.
Linear search is a sequential search algorithm that checks each element of an array until the target element is found. It has a worst-case time complexity of O(n) where n is the number of elements. Binary search is a divide and conquer algorithm that compares the target to the middle element of a sorted array, eliminating half of the remaining elements with each comparison. It has a time complexity of O(log n). Common sorting algorithms like bubble sort, insertion sort, and selection sort have a time complexity of O(n^2) as they may require up to n^2 comparisons in the worst case.
Linear search is a simple algorithm that checks each item in a collection one by one to find a match. It has complexity of O(n). Binary search is faster with complexity of O(log n) but requires the collection to be sorted. It works by repeatedly dividing the search range in half and checking the middle element to determine the range to search next until the target value is found or ruled out.
The document discusses various searching, sorting, and hashing techniques used in data structures and algorithms. It describes linear and binary search methods for finding elements in a list or array. It also explains bubble, insertion, selection, and shell sort algorithms for arranging elements in ascending or descending order. Finally, it covers hashing techniques like hash functions, separate chaining, and open addressing that are used to map keys to values in a hash table.
This document discusses different sorting algorithms including insertion sort, selection sort, and shell sort. It provides examples of how each algorithm works and pseudocode for implementation. Insertion sort iterates through an array and inserts each element into its sorted position. Selection sort finds the minimum element in each pass and swaps it into the front. Shell sort improves on insertion sort by comparing elements separated by gaps to sort sublists and gradually reduce the gaps.
The document describes the Towers of Hanoi problem and algorithms for solving it recursively. It involves moving n disks from one pole to another, where disks can only be moved one at a time and no disk can be placed on top of a smaller disk. The recursive algorithm solvesTowers moves the top n-1 disks to the spare pole, then the last disk to the destination pole, then the n-1 disks from the spare pole to the destination pole. The document also discusses linear and binary search algorithms and their recursive implementations.
This document summarizes the pseudocode and time complexity for three sorting/searching algorithms:
1) Linear search has a time complexity of O(n) and searches a list sequentially to find a matching item.
2) Binary search has a time complexity of O(log n) and searches a sorted array by repeatedly dividing the search interval in half.
3) Bubble sort has a time complexity of O(n^2) and iterates through a list, comparing and swapping adjacent elements into ascending order.
In the binary search, if the array being searched has 32 elements in.pdfarpitaeron555
In the binary search, if the array being searched has 32 elements in it, how many elements of the
array must be examined to be certain that the array does not contain the key? What about 1024
elements? Note: the answer is the same regardless of whether the algorithm is recursive or
iterative.
Solution
Binary Search Algorithm- Fundamentals, Implementation and Analysis
Hitesh Garg | May 15, 2015 | algorithms | 5 Comments
Binary Search Algorithm and its Implementation
In our previous tutorial we discussed about Linear search algorithm which is the most basic
algorithm of searching which has some disadvantages in terms of time complexity,so to
overcome them to a level an algorithm based on dichotomic (i.e. selection between two distinct
alternatives) divide and conquer technique is used i.e. Binarysearch algorithm and it is used to
find an element in a sorted array (yes, it is a prerequisite for this algorithm and a limitation too).
In this algorithm we use the sorted array so as to reduce the time complexity to O(log n). In this,
size of the elements reduce to half after each iteration and this is achieved by comparing the
middle element with the key and if they are unequal then we choose the first or second half,
whichever is expected to hold the key (if available) based on the comparison i.e. if array is sorted
in an increasing manner and the key is smaller than middle element than definitely if key exists,
it will be in the first half, we chose it and repeat same operation again and again until key is
found or no more elements are left in the array.
Recursive Pseudocode:
1
2
3
4
5
6
7
8
9
10
11
12
// initially called with low = 0, high = N – 1
BinarySearch_Right(A[0..N-1], value, low, high) {
// invariants: value >= A[i] for all i < low
value < A[i] for all i > high
if (high < low)
return low
mid = low +((high – low) / 2) // THIS IS AN IMPORTANT STEP TO AVOID BUGS
if (A[mid] > value)
return BinarySearch_Right(A, value, low, mid-1)
else
return BinarySearch_Right(A, value, mid+1, high)
}
Iterative Pseudocode:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
BinarySearch_Right(A[0..N-1], value) {
low = 0
high = N - 1
while (low <= high) {
// invariants: value >= A[i] for all i < low
value < A[i] for all i > high
mid = low +((high – low) / 2) // THIS IS AN IMPORTANT STEP TO AVOID BUGS
if (A[mid] > value)
high = mid - 1
else
low = mid + 1
}
return low
}
Asymptotic Analysis
Since this algorithm halves the no of elements to be checked after every iteration it will take
logarithmic time to find any element i.e. O(log n) (where n is number of elements in the list) and
its expected cost is also proportional to log n provided that searching and comparing cost of all
the elements is same
Data structure used -> Array
Worst case performance -> O(log n)
Best case performance -> O(1)
Average case performance -> O(log n)
Worst case space complexity -> O(1)
So the idea is-
RECURSIVE Implementation of Binary search in C programming language
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
.
A one-dimensional array stores elements linearly such that they can be accessed using an index, the document provides an example of finding the address of an element in a 1D array and taking user input to store in an array and display all elements, and abstract data types provide only the interface of a data structure without implementation details.
This is an archive of general information about a technical subject of computing. Information technology (IT) is a set of related fields that encompass computer systems, software, programming languages and data and information processing and storage.[1] IT forms part of information and communications technology (ICT).[2] An information technology system (IT system) is generally an information system, a communications system, or, more specifically speaking, a computer system — including all hardware, software, and peripheral equipment — operated by a limited group of IT users, and an IT project usually refers to the commissioning and implementation of an IT system.[3]
Although humans have been storing, retrieving, manipulating, and communicating information since the earliest writing systems were developed,[4] the term information technology in its modern sense first appeared in a 1958 article published in the Harvard Business Review; authors Harold J. Leavitt and Thomas L. Whisler commented that "the new technology does not yet have a single established name. We shall call it information technology (IT)."[5] Their definition consists of three categories: techniques for processing, the application of statistical and mathematical methods to decision-making, and the simulation of higher-order thinking through computer programs.[5]
This document provides an overview of sorting algorithms including bubble sort, insertion sort, shellsort, and others. It discusses why sorting is important, provides pseudocode for common sorting algorithms, and gives examples of how each algorithm works on sample data. The runtime of sorting algorithms like insertion sort and shellsort are analyzed, with insertion sort having quadratic runtime in the worst case and shellsort having unknown but likely better than quadratic runtime.
1. The document discusses various data structures concepts including arrays, dynamic arrays, operations on arrays like traversing, insertion, deletion, sorting, and searching.
2. It provides examples of declaring and initializing arrays, as well as dynamic array allocation using pointers and new/delete operators.
3. Searching techniques like linear search and binary search are explained, with linear search comparing each element sequentially while binary search eliminates half the elements at each step for sorted arrays.
The document discusses arrays, searching, and sorting algorithms. It defines arrays and how they are declared and initialized. It then discusses linear search and binary search algorithms for searching arrays. It also covers bubble sort for sorting arrays. Code examples are provided for calculating the average of an array, linear search, binary search, and bubble sort. Computational complexity is discussed, showing binary search requires O(log n) time while linear search requires O(n) time.
Tree is a hierarchical data structure that can be represented non-linearly. A tree contains a finite set of elements connected by parent-child relationships, with each element having zero or more subtrees. Binary trees restrict each element to having at most two child subtrees. Binary search trees organize values such that all left subtree values are less than the parent and all right subtree values are greater than the parent, allowing fast searches that take logarithmic time on average. Common tree traversals include inorder (left, root, right), preorder (root, left, right), and postorder (left, right, root).
- Data structures allow for efficient processing and organization of large volumes of data. They define logical relationships between related data elements and how operations like storage, retrieval, and access are carried out on the data.
- Common data structures include arrays, lists, stacks, queues, trees, graphs, dictionaries, maps, hash tables, sets, and lattices. Linear data structures like arrays and lists store elements in a linear order, while non-linear structures like trees and graphs have more complex relationships between elements.
- Linked lists are a data structure where each element contains a link to the next element, rather than using contiguous memory locations. This allows for more flexible insertion and deletion than arrays. Doubly linked lists add a link to
1. The document discusses various C programming concepts like typedef, structures, bitfields, enumerations, files, streams, file I/O functions, text files vs binary files, and random access files.
2. It provides examples of defining structures with and without typedef, creating bitfields to optimize memory usage, using enumerations to make code more readable, opening, reading and writing to files, and performing random access operations on files.
3. The key file I/O functions discussed are fopen(), fclose(), fgetc(), fputc(), fprintf(), fscanf(), ftell(), fseek(), rewind() for performing various file operations.
The document discusses C data types including primary, derived, and user-defined data types. It provides details on array and structure data types. Structures allow grouping of related data of different types under a single name. Structures can contain nested structures and pointers to structures. Pointers to structures allow accessing structure members using dot and arrow operators. Arrays of structures and self-referential structures are also discussed.
The document discusses functions and modularity in code. Key points include:
1. Functions allow code to be reused by defining independent and reusable modules that can be called by name.
2. Functions receive input parameters, perform operations, and return outputs. Calling functions transfer control to the function, which then returns control back to the calling function.
3. Functions can be categorized based on whether they have parameters, return values, or both. They can also use different storage classes like static, external and automatic that determine variable scope and lifetime.
The document summarizes the basic components of a computer system including input devices, output devices, storage areas, and the microprocessor. It shows how these components interact and describes the flow of data through the system from input to output.
CouponTango is made up of daily deal addicts and lovers. We love the savings provided by daily deals and quickly got addicted to purchasing great deals from multiple sites such as Groupon, LivingSocial, Tippr, TownHog, KGBDeals, and many more. However, we quickly discovered:
Each of us was hunting across a number of daily deal sites to find the deal that matched our individual preferences
Our inboxes were filling up with daily deal emails
Keeping track of all of the deals we purchased across multiple daily deal sites was time consuming and we were forgetting what was where a large portion of the deals purchased we didn't get around to using before the promotional period expired
Thus was born the inspiration for CouponTango.
Taking AI to the Next Level in Manufacturing.pdfssuserfac0301
Read Taking AI to the Next Level in Manufacturing to gain insights on AI adoption in the manufacturing industry, such as:
1. How quickly AI is being implemented in manufacturing.
2. Which barriers stand in the way of AI adoption.
3. How data quality and governance form the backbone of AI.
4. Organizational processes and structures that may inhibit effective AI adoption.
6. Ideas and approaches to help build your organization's AI strategy.
Your One-Stop Shop for Python Success: Top 10 US Python Development Providersakankshawande
Simplify your search for a reliable Python development partner! This list presents the top 10 trusted US providers offering comprehensive Python development services, ensuring your project's success from conception to completion.
Fueling AI with Great Data with Airbyte WebinarZilliz
This talk will focus on how to collect data from a variety of sources, leveraging this data for RAG and other GenAI use cases, and finally charting your course to productionalization.
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...Jeffrey Haguewood
Sidekick Solutions uses Bonterra Impact Management (fka Social Solutions Apricot) and automation solutions to integrate data for business workflows.
We believe integration and automation are essential to user experience and the promise of efficient work through technology. Automation is the critical ingredient to realizing that full vision. We develop integration products and services for Bonterra Case Management software to support the deployment of automations for a variety of use cases.
This video focuses on integration of Salesforce with Bonterra Impact Management.
Interested in deploying an integration with Salesforce for Bonterra Impact Management? Contact us at sales@sidekicksolutionsllc.com to discuss next steps.
5th LF Energy Power Grid Model Meet-up SlidesDanBrown980551
5th Power Grid Model Meet-up
It is with great pleasure that we extend to you an invitation to the 5th Power Grid Model Meet-up, scheduled for 6th June 2024. This event will adopt a hybrid format, allowing participants to join us either through an online Mircosoft Teams session or in person at TU/e located at Den Dolech 2, Eindhoven, Netherlands. The meet-up will be hosted by Eindhoven University of Technology (TU/e), a research university specializing in engineering science & technology.
Power Grid Model
The global energy transition is placing new and unprecedented demands on Distribution System Operators (DSOs). Alongside upgrades to grid capacity, processes such as digitization, capacity optimization, and congestion management are becoming vital for delivering reliable services.
Power Grid Model is an open source project from Linux Foundation Energy and provides a calculation engine that is increasingly essential for DSOs. It offers a standards-based foundation enabling real-time power systems analysis, simulations of electrical power grids, and sophisticated what-if analysis. In addition, it enables in-depth studies and analysis of the electrical power grid’s behavior and performance. This comprehensive model incorporates essential factors such as power generation capacity, electrical losses, voltage levels, power flows, and system stability.
Power Grid Model is currently being applied in a wide variety of use cases, including grid planning, expansion, reliability, and congestion studies. It can also help in analyzing the impact of renewable energy integration, assessing the effects of disturbances or faults, and developing strategies for grid control and optimization.
What to expect
For the upcoming meetup we are organizing, we have an exciting lineup of activities planned:
-Insightful presentations covering two practical applications of the Power Grid Model.
-An update on the latest advancements in Power Grid -Model technology during the first and second quarters of 2024.
-An interactive brainstorming session to discuss and propose new feature requests.
-An opportunity to connect with fellow Power Grid Model enthusiasts and users.
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUpanagenda
Webinar Recording: https://www.panagenda.com/webinars/hcl-notes-und-domino-lizenzkostenreduzierung-in-der-welt-von-dlau/
DLAU und die Lizenzen nach dem CCB- und CCX-Modell sind für viele in der HCL-Community seit letztem Jahr ein heißes Thema. Als Notes- oder Domino-Kunde haben Sie vielleicht mit unerwartet hohen Benutzerzahlen und Lizenzgebühren zu kämpfen. Sie fragen sich vielleicht, wie diese neue Art der Lizenzierung funktioniert und welchen Nutzen sie Ihnen bringt. Vor allem wollen Sie sicherlich Ihr Budget einhalten und Kosten sparen, wo immer möglich. Das verstehen wir und wir möchten Ihnen dabei helfen!
Wir erklären Ihnen, wie Sie häufige Konfigurationsprobleme lösen können, die dazu führen können, dass mehr Benutzer gezählt werden als nötig, und wie Sie überflüssige oder ungenutzte Konten identifizieren und entfernen können, um Geld zu sparen. Es gibt auch einige Ansätze, die zu unnötigen Ausgaben führen können, z. B. wenn ein Personendokument anstelle eines Mail-Ins für geteilte Mailboxen verwendet wird. Wir zeigen Ihnen solche Fälle und deren Lösungen. Und natürlich erklären wir Ihnen das neue Lizenzmodell.
Nehmen Sie an diesem Webinar teil, bei dem HCL-Ambassador Marc Thomas und Gastredner Franz Walder Ihnen diese neue Welt näherbringen. Es vermittelt Ihnen die Tools und das Know-how, um den Überblick zu bewahren. Sie werden in der Lage sein, Ihre Kosten durch eine optimierte Domino-Konfiguration zu reduzieren und auch in Zukunft gering zu halten.
Diese Themen werden behandelt
- Reduzierung der Lizenzkosten durch Auffinden und Beheben von Fehlkonfigurationen und überflüssigen Konten
- Wie funktionieren CCB- und CCX-Lizenzen wirklich?
- Verstehen des DLAU-Tools und wie man es am besten nutzt
- Tipps für häufige Problembereiche, wie z. B. Team-Postfächer, Funktions-/Testbenutzer usw.
- Praxisbeispiele und Best Practices zum sofortigen Umsetzen
This presentation provides valuable insights into effective cost-saving techniques on AWS. Learn how to optimize your AWS resources by rightsizing, increasing elasticity, picking the right storage class, and choosing the best pricing model. Additionally, discover essential governance mechanisms to ensure continuous cost efficiency. Whether you are new to AWS or an experienced user, this presentation provides clear and practical tips to help you reduce your cloud costs and get the most out of your budget.
Digital Banking in the Cloud: How Citizens Bank Unlocked Their MainframePrecisely
Inconsistent user experience and siloed data, high costs, and changing customer expectations – Citizens Bank was experiencing these challenges while it was attempting to deliver a superior digital banking experience for its clients. Its core banking applications run on the mainframe and Citizens was using legacy utilities to get the critical mainframe data to feed customer-facing channels, like call centers, web, and mobile. Ultimately, this led to higher operating costs (MIPS), delayed response times, and longer time to market.
Ever-changing customer expectations demand more modern digital experiences, and the bank needed to find a solution that could provide real-time data to its customer channels with low latency and operating costs. Join this session to learn how Citizens is leveraging Precisely to replicate mainframe data to its customer channels and deliver on their “modern digital bank” experiences.
A Comprehensive Guide to DeFi Development Services in 2024Intelisync
DeFi represents a paradigm shift in the financial industry. Instead of relying on traditional, centralized institutions like banks, DeFi leverages blockchain technology to create a decentralized network of financial services. This means that financial transactions can occur directly between parties, without intermediaries, using smart contracts on platforms like Ethereum.
In 2024, we are witnessing an explosion of new DeFi projects and protocols, each pushing the boundaries of what’s possible in finance.
In summary, DeFi in 2024 is not just a trend; it’s a revolution that democratizes finance, enhances security and transparency, and fosters continuous innovation. As we proceed through this presentation, we'll explore the various components and services of DeFi in detail, shedding light on how they are transforming the financial landscape.
At Intelisync, we specialize in providing comprehensive DeFi development services tailored to meet the unique needs of our clients. From smart contract development to dApp creation and security audits, we ensure that your DeFi project is built with innovation, security, and scalability in mind. Trust Intelisync to guide you through the intricate landscape of decentralized finance and unlock the full potential of blockchain technology.
Ready to take your DeFi project to the next level? Partner with Intelisync for expert DeFi development services today!
Best 20 SEO Techniques To Improve Website Visibility In SERPPixlogix Infotech
Boost your website's visibility with proven SEO techniques! Our latest blog dives into essential strategies to enhance your online presence, increase traffic, and rank higher on search engines. From keyword optimization to quality content creation, learn how to make your site stand out in the crowded digital landscape. Discover actionable tips and expert insights to elevate your SEO game.
Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...Tatiana Kojar
Skybuffer AI, built on the robust SAP Business Technology Platform (SAP BTP), is the latest and most advanced version of our AI development, reaffirming our commitment to delivering top-tier AI solutions. Skybuffer AI harnesses all the innovative capabilities of the SAP BTP in the AI domain, from Conversational AI to cutting-edge Generative AI and Retrieval-Augmented Generation (RAG). It also helps SAP customers safeguard their investments into SAP Conversational AI and ensure a seamless, one-click transition to SAP Business AI.
With Skybuffer AI, various AI models can be integrated into a single communication channel such as Microsoft Teams. This integration empowers business users with insights drawn from SAP backend systems, enterprise documents, and the expansive knowledge of Generative AI. And the best part of it is that it is all managed through our intuitive no-code Action Server interface, requiring no extensive coding knowledge and making the advanced AI accessible to more users.
Skybuffer SAM4U tool for SAP license adoptionTatiana Kojar
Manage and optimize your license adoption and consumption with SAM4U, an SAP free customer software asset management tool.
SAM4U, an SAP complimentary software asset management tool for customers, delivers a detailed and well-structured overview of license inventory and usage with a user-friendly interface. We offer a hosted, cost-effective, and performance-optimized SAM4U setup in the Skybuffer Cloud environment. You retain ownership of the system and data, while we manage the ABAP 7.58 infrastructure, ensuring fixed Total Cost of Ownership (TCO) and exceptional services through the SAP Fiori interface.
For the full video of this presentation, please visit: https://www.edge-ai-vision.com/2024/06/temporal-event-neural-networks-a-more-efficient-alternative-to-the-transformer-a-presentation-from-brainchip/
Chris Jones, Director of Product Management at BrainChip , presents the “Temporal Event Neural Networks: A More Efficient Alternative to the Transformer” tutorial at the May 2024 Embedded Vision Summit.
The expansion of AI services necessitates enhanced computational capabilities on edge devices. Temporal Event Neural Networks (TENNs), developed by BrainChip, represent a novel and highly efficient state-space network. TENNs demonstrate exceptional proficiency in handling multi-dimensional streaming data, facilitating advancements in object detection, action recognition, speech enhancement and language model/sequence generation. Through the utilization of polynomial-based continuous convolutions, TENNs streamline models, expedite training processes and significantly diminish memory requirements, achieving notable reductions of up to 50x in parameters and 5,000x in energy consumption compared to prevailing methodologies like transformers.
Integration with BrainChip’s Akida neuromorphic hardware IP further enhances TENNs’ capabilities, enabling the realization of highly capable, portable and passively cooled edge devices. This presentation delves into the technical innovations underlying TENNs, presents real-world benchmarks, and elucidates how this cutting-edge approach is positioned to revolutionize edge AI across diverse applications.
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
C Language Unit-6
1. Searching techniques
Searching :
It is a process to find whether a particular value with specified properties is present or not
among a collection of items.
If the value is present in the collection, then searching is said to be successful, and it
returns the location of the value in the array.
Otherwise, if the value is not present in the array, the searching process displays the
appropriate message and in this case searching is said to be unsuccessful.
1) Linear or Sequential Searching 2) Binary Searching
int main( ) { Linear_Search (A[ ], N, val , pos )
int arr [ 50 ] , num , i , n , pos = -1; Step 1 : Set pos = -1 and k = 0
printf ("How many elements to sort : "); Step 2 : Repeat while k < N
scanf ("%d", &n); Begin
printf ("n Enter the elements : nn"); Step 3 : if A[ k ] = val
for( i = 0; i < n; i++ ) { Set pos = k
printf (“arr [%d ] : “ , i ); print pos
scanf( "%d", &arr[ i ] ); Goto step 5
} End while
printf(“nEnter the number to be searched : “); Step 4 : print “Value is not present”
scanf(“%d”,&num); Step 5 : Exit
for(i=0;i<n;i++)
if( arr [ i ] == num ) { Searches
pos = i ; break; -- for each item one by one in the list from
} the first, until the match is found.
if ( pos == -1 ) printf(“ %d does not exist ”,num); Efficiency of Linear search :
else -- Executes in O ( n ) times where n is the
printf(“ %d is found at location : %d”, num , pos); number of elements in the list.
2. Binary Searching
Algorithm:
• Before searching, the list of items should be sorted in ascending order.
• We first compare the key value with the item in the position of the array. If there is a match, we
can return immediately the position.
• if the value is less than the element in middle location of the array, the required value is lie in
the lower half of the array.
• if the value is greater than the element in middle location of the array, the required value is lie
in the upper half of the array.
• We repeat the above procedure on the lower half or upper half of the array.
Binary_Search (A [ ], U_bound, VAL)
Step 1 : set BEG = 0 , END = U_bound , POS = -1
Step 2 : Repeat while (BEG <= END ) void binary_serch ( int a [], int n, int val ) {
Step 3 : set MID = ( BEG + END ) / 2 int end = n - 1, beg = 0, pos = -1;
Step 4 : if A [ MID ] == VAL then while( beg <= end ) {
POS = MID mid = ( beg + end ) / 2;
print VAL “ is available at “, POS if ( val == a [ mid ] ) {
GoTo Step 6 pos = mid;
End if printf(“%d is available at %d”,val, pos );
if A [ MID ] > VAL then break;
set END = MID – 1 }
Else if ( a [ mid ] > val ) end = mid – 1;
set BEG = MID + 1 else beg = mid + 1;
End if }
End while if ( pos = - 1)
Step 5 : if POS = -1 then printf( “%d does not exist “, val );
print VAL “ is not present “ }
End if
Step 6 : EXIT
3. Sorting
Sorting is a technique to rearrange the elements of a list in ascending or
descending order, which can be numerical, lexicographical, or any user-defined order.
Ranking of students is the process of sorting in descending order.
EMCET Ranking is an example for sorting with user-defined order.
EMCET Ranking is done with the following priorities.
i) First priority is marks obtained in EMCET.
ii) If marks are same, the ranking will be done with comparing marks obtained in
the Mathematics subject.
iii) If marks in Mathematics subject are also same, then the date of births will be
compared.
Internal Sorting : Types of Internal Sortings
If all the data that is to be sorted can be accommodated
at a time in memory is called internal sorting. Bubble Sort
External Sorting : Insertion Sort
It is applied to Huge amount of data that cannot be Selection Sort
accommodated in memory all at a time. So data in disk
or file is loaded into memory part by part. Each part that Quick Sort
is loaded is sorted separately, and stored in an
intermediate file and all parts are merged into one single Merge Sort
sorted list.
4. Bubble Sort
Bubbles up the highest
Unsorted Sorted
Bubble_Sort ( A [ ] , N )
Step 1 : Repeat For P = 1 to N – 1
10 54 54 54 54 54 Begin
Step 2 : Repeat For J = 1 to N – P
47 10 47 47 47 47 Begin
Step 3 : If ( A [ J ] < A [ J – 1 ] )
12 47 10 23 23 23 Swap ( A [ J ] , A [ J – 1 ] )
End For
54 12 23 10 19 19 End For
Step 4 : Exit
19 23 12 19 10 12
Complexity of Bubble_Sort
23 19 19 12 12 10 The complexity of sorting algorithm is
depends upon the number of comparisons
Original After After After After After that are made.
List Pass 1 Pass 2 Pass 3 Pass 4 Pass 5 Total comparisons in Bubble sort is
n ( n – 1) / 2 ≈ n 2 – n
Complexity = O ( n 2 )
5. void print_array (int a[ ], int n) {
int i;
for (i=0;I < n ; i++) printf("%5d",a[ i ]);
Bubble Sort
}
void bubble_sort ( int arr [ ], int n) {
int pass, current, temp;
For pass = 1 to N - 1
for ( pass=1;(pass < n) ;pass++) {
for ( current=1;current <= n – pass ; current++) {
if ( arr[ current - 1 ] > arr[ current ] ) {
temp = arr[ current - 1 ]; For J = 1 to N - pass
arr[ current - 1 ] = arr[ current ];
arr[ current ] = temp;
} T
A[J–1]>A[J]
}
}
} F
int main() { Temp = A [ J – 1 ]
int count,num[50],i ; A[J–1]=A[J]
printf ("How many elements to be sorted : "); A [ J ] = Temp
scanf ("%d", &count);
printf("n Enter the elements : nn");
for ( i = 0; i < count; i++) {
printf ("num [%d] : ", i ); scanf( "%d", &num[ i ] );
}
printf("n Array Before Sorting : nnn");
print_array ( num, count );
Return
bubble_sort ( num, count);
printf("nnn Array After Sorting : nnn");
print_array ( num, count );
}
6. TEMP Insertion Sort
Insertion_Sort ( A [ ] , N )
78 23 45 8 32 36 Step 1 : Repeat For K = 1 to N – 1
23 Begin
Step 2 : Set Temp = A [ K ]
Step 3 : Set J = K – 1
23 78 45 8 32 36 Step 4 : Repeat while Temp < A [ J ] AND J >= 0
45 Begin
Set A [ J + 1 ] = A [ J ]
Set J = J - 1
23 45 78 8 32 36 End While
Step 5 : Set A [ J + 1 ] = Temp
8
End For
Step 4 : Exit
8 23 45 78 32 36
32 insertion_sort ( int A[ ] , int n ) {
int k , j , temp ;
8 23 32 45 78 36 for ( k = 1 ; k < n ; k++ ) {
temp = A [ k ] ;
36 j = k - 1;
while ( ( temp < A [ j ] ) && ( j >= 0 ) ) {
8 23 32 36 45 78 A[j+1] =A[j];
j--;
Complexity of Insertion Sort }
Best Case : O ( n ) A [ j + 1 ] = temp ;
Average Case : O ( n2 ) }
Worst Case : O ( n2 ) }
7. Smallest Selection Sort ( Select the smallest and Exchange )
Selection_Sort ( A [ ] , N )
8 23 78 45 8 32 56 Step 1 : Repeat For K = 0 to N – 2
Begin
Step 2 : Set POS = K
Step 3 : Repeat for J = K + 1 to N – 1
23 8 78 45 23 32 56 Begin
If A[ J ] < A [ POS ]
Set POS = J
32 8 23 45 78 32 56 End For
Step 5 : Swap A [ K ] with A [ POS ]
End For
Step 6 : Exit
45 8 23 32 78 45 56
selection_sort ( int A[ ] , int n ) {
int k , j , pos , temp ;
for ( k = 0 ; k < n - 1 ; k++ ) {
56 8 23 32 45 78 56 pos = k ;
for ( j = k + 1 ; j <= n ; j ++ ) {
if ( A [ j ] < A [ pos ] )
8 23 32 45 56 78 pos = j ;
}
temp = A [ k ] ;
Complexity of Selection Sort A [ k ] = A [ pos ] ;
Best Case : O ( n2 ) A [ pos ] = temp ;
Average Case : O ( n2 ) }
Worst Case : O ( n2 )
}
8. Selection sort
Insertion sort
k = 0; k < n - 1 ; k++
k = 1; k < n ; k++
pos = k
temp = a [ k ]
j=k-1
j = k + 1 ; j < n ; j++
temp < a [ j ] && j >= 0
a[ j ] < a[ pos ]
a[j+1]=a[j] pos = j
j=j-1
a [ j + 1 ] = temp temp = a[ k ]
a [ k ] = a [ pos ]
a [ pos ] = temp
return
return
9. Bubble sort – Insertion sort – Selection sort
Bubble Sort :
-- very primitive algorithm like linear search, and least efficient .
-- No of swappings are more compare with other sorting techniques.
-- It is not capable of minimizing the travel through the array like insertion sort.
Insertion Sort :
-- sorted by considering one item at a time.
-- efficient to use on small sets of data.
-- twice as fast as the bubble sort.
-- 40% faster than the selection sort.
-- no swapping is required.
-- It is said to be online sorting because it continues the sorting a list as and when it receives
new elements.
-- it does not change the relative order of elements with equal keys.
-- reduces unnecessary travel through the array.
-- requires low and constant amount of extra memory space.
-- less efficient for larger lists.
Selection sort :
-- No of swappings will be minimized. i.e., one swap on one pass.
-- generally used for sorting files with large objects and small keys.
-- It is 60% more efficient than bubble sort and 40% less efficient than insertion sort.
-- It is preferred over bubble sort for jumbled array as it requires less items to be exchanged.
-- uses internal sorting that requires more memory space.
-- It cannot recognize sorted list and carryout the sorting from the beginning, when new elements
are added to the list.
10. Quick Sort – A recursive process of sorting
Original-list of 11 elements :
8 3 2 11 5 14 0 2 9 4 20 Algorithm for Quick_Sort :
Set list [ 0 ] as pivot : -- set the element A [ start_index ] as pivot.
-- rearrange the array so that :
pivot
-- all elements which are less than the pivot
come left ( before ) to the pivot.
8 3 2 11 5 14 0 2 9 4 20 -- all elements which are greater than the pivot
come right ( after ) to the pivot.
Rearrange ( partition ) the elements -- recursively apply quick-sort on the sub-list of
into two sub lists : lesser elements.
pivot -- recursively apply quick-sort on the sub-list of
greater elements.
8 -- the base case of the recursion is lists of size
4 3 2 2 5 0 11 9 14 20
zero or one, which are always sorted.
Sub-list of Sub-list of
lesser elements greater elements
Complexity of Quick Sort
Best Case : O ( n log n )
Apply Quick-sort Apply Quick-sort Average Case : O ( n log n )
recursively recursively Worst Case : O ( n2 )
on sub-list on sub-list
12. Quick Sort – Program
int partition ( int a [ ], int beg, int end ) { void quick_sort(int a[ ] , int beg , int end ) {
int left , right , loc , flag = 0, pivot ; int loc;
loc = left = beg; if ( beg < end ) {
right = end; loc = partition( a , beg , end );
pivot = a [ loc ] ; quick_sort ( a , beg , loc – 1 );
while ( flag == 0 ) quick_sort ( a , loc + 1 , end );
{ }
while( (pivot <= a [ right ] )&&( loc != right ) ) }
right - - ; void print_array (int a [ ],int n) {
if( loc == right ) flag = 1; int i;
else { for ( i = 0 ; I < n ; i++ ) printf( "%5d“ ,a [ i ] ) ;
a [ loc ] = a [ right ] ; }
left = loc + 1 ; int main () {
loc = right; int count , num[ 50 ] , i ;
} printf ("How many elements to sort : ");
while ( (pivot >= a [ left ] ) && ( loc != left ) ) scanf ("%d", &count );
left++; printf ("n Enter the elements : nn");
if( loc == left ) flag = 1; for( i = 0; i < count; i++ ) {
else { printf ("num [%d ] : “ , i );
a [ loc ] = a [ left ] ; scanf( "%d", &num[ i ] );
right = loc - 1; }
loc = left; printf (“ n Array Before Sorting : nnn“ );
} print_array ( num , count ) ;
} quick_sort ( num ,0 , count-1) ;
a [ loc ] = pivot; printf ( "nnn Array After Sorting : nnn“ );
return loc; print_array ( num , count );
} }
13. partition ( int a [ ], int beg, int end ) A B
loc = left = beg F T
loc == left
flag = 0, right = end
pivot = a [ loc ]
a [ loc ] = a [ left ] flag = 1
Flag == 0 right = loc - 1 ;
loc = left;
pivot <= a [ right ]
&& loc != right
a[ loc ] = pivot
right = right - 1
return loc
F T
loc == right quick_sort ( int a [ ], int beg, int end )
a [ loc ] = a [ right ] flag = 1 F T
left = loc + 1 ; loc == left
loc = right;
loc = partition( a , beg , end )
pivot >= a [ left ]
&&loc != left quick_sort ( a , beg , end )
left = left + 1 quick_sort ( a , beg , end )
return
A B
14. Merge Sort ( Divide and conquer )
Divide the array
-- Merge sort technique sorts a given set
39 9 81 45 90 27 72 18 of values by combining two sorted
arrays into one larger sorted arrays.
-- A small list will take fewer steps to sort
39 9 81 45 90 27 72 18 than a large list.
-- Fewer steps are required to construct
a sorted list from two sorted lists than
39 9 81 45 90 27 72 18 two unsorted lists.
-- You only have to traverse each list
39 9 81 45 90 27 72 18 once if they're already sorted .
Merge the elements to sorted array Merge_sort Algorithm
2. If the list is of length 0 or 1, then it is already
sorted.
39 9 81 45 90 27 72 18 Otherwise:
5. Divide the unsorted list into two sublists of
about half the size.
9 39 45 81 27 90 18 72 3. Sort each sublist recursively by re-applying
merge sort.
8. Merge the two sublists back into one
9 39 45 81 18 27 72 90 sorted list.
Time complexity
9 18 27 39 45 72 81 90 Worst case - O(n log n)
Best case - O(nlogn) typical, O(n) natural variant
Average case - O( n log n )
15. Merge Sort - Program
void merge(int a[ ],int low,int high,int mid){
int i, j, k, c[50];
i=low; j=mid+1; k=low;
while( ( i<=mid )&&( j <= high ) ) { void print_array (int a [ ],int n) {
int i;
if( a[ i ]<a[ j ] ){ for ( i = 0 ; I < n ; i++ ) printf( "%5d“ ,a [ i ] ) ;
c[ k ]=a[ i ]; k++; i++; }
}else { int main () {
c[ k ]=a[ j ]; k++; j++; int count , num[ 50 ] , i ;
} printf ("How many elements to sort : ");
} scanf ("%d", &count );
while( i<=mid ) { c[k]=a[ i ]; k++; i++; } printf ("n Enter the elements : nn");
for( i = 0; i < count; i++ ) {
while(j<=high) { c[k]=a[ j ]; k++; j++; } printf ("num [%d ] : “ , i );
for(i=low;i<k;i++) a[ i ]=c[ i ]; scanf( "%d", &num[ i ] );
} }
printf (“ n Array Before Sorting : nnn“ );
void merge_sort(int a[ ], int low, int high){
print_array ( num , count ) ;
int mid;
merge_sort ( num ,0 , count-1) ;
if( low < high) {
printf ( "nnn Array After Sorting : nnn“ );
mid=(low+high)/2; print_array ( num , count );
merge_sort (a, low, mid); }
merge_sort (a, mid+1 ,high);
merge (a, low, high, mid);
}
}
16. merge
i =low ; j = mid+1;k = low
Merge_Sort
i <= mid && j <= high
T F T
F low < high
a[ i ] < a[ j ]
c[ k ] =a [ i ] ; c[ k ] =a [ j ] ; mid = ( low + high ) / 2
k++ ; i++ k++ ; j++
merge_sort (a, low, mid)
i <= mid
merge_sort (a, mid, high )
c[ k ] =a [ i ] ; k++ ; i++
Merge (a, low,high , mid)
j <= high
c[ k ] =a [ j ] ; k++ ; j++
i = low ; i < k ; i ++
Return
a[ i ] = c [ i ]
return