Sorting is an important technique which every programmer should know. Here is my part to explain you the three basic sorting methodologies.For any queries kindly comment in the comment section.
The document provides information about data structures and algorithms. It defines key terms like data, information, data structure, algorithm and different types of algorithms. It discusses linear data structures like arrays, operations on arrays like traversing, searching, inserting and deleting elements. It also covers recursive functions, recursion concept, searching algorithms like sequential search and binary search along with their algorithms and examples.
This document provides an overview of advanced data structures and algorithm analysis taught by Dr. Sukhamay Kundu at Louisiana State University. It discusses the role of data structures in making computations faster by supporting efficient data access and storage. The document distinguishes between algorithms, which determine the computational steps and data access order, and data structures, which enable efficient reading and writing of data. It also describes different methods for measuring algorithm performance, such as theoretical time complexity analysis and empirical measurements. Examples are provided for instrumenting code to count operations. Overall, the document introduces fundamental concepts about algorithms and data structures.
According to the document:
1. A function is defined as a rule that assigns each input exactly one output. The graph of a function is a set of ordered pairs consisting of an input and its corresponding output.
2. In functions, the input and output generally refer to the x and y values of an equation. For example, in the equation y=2x+1, an input is substituted for x and the resulting output is the value of y.
3. For a set of ordered pairs to be a function, there can be no repeated inputs, as each input must correspond to only one output. Examples are provided to illustrate this.
The document discusses recursion and provides examples of recursive functions and algorithms including:
1) A recursive function to calculate the sum of an arithmetic series. It breaks the problem down into smaller sub-problems by recursively calling itself to calculate successive terms until the base case is reached.
2) Binary search illustrated recursively by dividing the search space in half on each recursive call until the target value is found or the space is empty.
3) Mergesort explained as a divide and conquer algorithm that recursively sorts sublists until lists of size 1 are reached and then merges the sorted sublists.
The document discusses the C++ Standard Template Library (STL) unordered_set and set containers.
[1] The unordered_set stores unique elements in no particular order, allowing fast retrieval with average O(1) time complexity for search, insertion, and removal.
[2] The set stores unique elements in a particular order determined by a comparison function, with average O(logN) time complexity for search, insertion, and removal.
The document discusses the history and basics of SQL. It provides an overview of SQL commands like SELECT, INSERT, UPDATE, DELETE and how they allow users to query, manipulate and manage data in a relational database. Examples are shown of how to retrieve, insert, modify and delete data using SQL statements. Data types supported in SQL databases like Access and Oracle are also outlined.
The document discusses recursion and provides examples of recursive algorithms and data structures including arithmetic series, Fibonacci sequence, binary search, and mergesort. Recursion involves breaking a problem down into smaller sub-problems until they can be solved directly, and combining the solutions to solve the original problem. Examples demonstrate how recursion uses function calls to solve problems by dividing them into base cases and recursively calling itself on smaller instances.
This document discusses various concepts in R including reading and writing data files, lists, data frames, conditional statements, loops, and functions. It explains how to read data from files using read.table() and write data to files using write.table(). Lists can be used to store heterogeneous data in a single object. Data frames allow storing data in a tabular form with rows and columns. Conditional statements like if/else and loops like for and while allow repeating blocks of code. Functions are objects that return a value for given arguments.
This document discusses hashing and related concepts:
- Hashing involves using a hash function to map keys to table indices in an array. Collisions occur when distinct keys hash to the same index.
- Collision resolution techniques include separate chaining, which stores keys that collide in a linked list at the index, and open addressing, which probes for the next empty slot when a collision occurs.
- Good hash functions aim to distribute keys uniformly among indices and avoid collisions. Properties like using the whole key and producing random-looking results are desirable.
- Hashing has applications beyond symbol tables, including data mining text and genomes by representing documents as vectors based on hashed subsequences.
The document discusses data structures and algorithms. It defines arrays as a series of objects of the same size and type, where each object is an element that can be accessed via an index. Algorithms are described as finite sequences of instructions to solve problems, with analysis of algorithms determining the resources like time and storage required.
This is a presentation on Arrays, one of the most important topics on Data Structures and algorithms. Anyone who is new to DSA or wants to have a theoretical understanding of the same can refer to it :D
The document discusses dynamic memory allocation and linked lists in C programming. It covers the key concepts of:
- Dynamic memory allocation functions like malloc(), calloc(), free(), and realloc() which are used to allocate and free memory during runtime.
- The differences between arrays and linked lists, with linked lists being a dynamic data structure that can grow and shrink in size more efficiently than arrays.
- How to create, traverse, insert, delete and perform other operations on singly and doubly linked lists using C pointers and memory allocation functions. Examples code is provided to demonstrate creating and manipulating linked lists.
The document discusses two standard template library containers for storing key-value pairs: unordered_map and map. Unordered_map uses a hash table to provide fast lookup of elements in average O(1) time, but the elements are in random order. Map uses a binary search tree to provide O(logN) lookup time and stores elements in sorted order. Both support insertion, erasure, and lookup of elements using similar functions but have different underlying implementations and time complexities.
Why you should care about functional programmingDhananjay Nene
The document discusses the benefits of functional programming including testability, easier integration, concurrency without locking, ability to leverage multicore processors, and brevity. It provides examples of functional programming concepts like higher order functions, pattern matching, and persistent data structures. While retraining the brain for a functional approach has an initial cost, the actual development costs are likely to be lower due to programs being smaller and cleaner with a focus on intent over implementation details.
An array is a collection of variables of the same type referenced by a common name. A structure groups variables of different types. An array of structures combines these concepts by creating an array where each element is a structure. For example, an array of fraction structures could be defined to hold multiple fractions. Each structure element in the array contains a numerator and denominator integer. The entire array of structures occupies a contiguous block of memory with each structure taking up the same amount of space. Individual structure elements can then be accessed using the array index and dot notation.
The document discusses data structures and lists in Python. It begins by defining data structures as a way to organize and store data for efficient access and modification. It then covers the different types of data structures, including primitive structures like integers and strings, and non-primitive structures like lists, tuples, and dictionaries. A large portion of the document focuses on lists in Python, describing how to perform common list manipulations like adding and removing elements using various methods. These methods include append(), insert(), remove(), pop(), and clear(). The document also discusses accessing list elements and other list operations such as sorting, counting, and reversing.
This document discusses various data structures in C#, including arrays, lists, queues, stacks, hash tables, and more. It provides code examples and explains the time complexity of common operations for each data structure. Asymptotic analysis and big-O notation are introduced for analyzing how efficiently a data structure handles operations as its size increases.
Data Structure Introduction
Data Structure Definition
Data Structure Types
Data Structure Characteristics
Need for Data Structure
Stack Definition
Stack Representation
Stack Operations
Stack Algorithm
Program for Stack in C++
Linked List Definition
Linked List Representation
Linked List Operations
Linked List Algorithm
Program for Linked List in C++
Linked List Defination
Linked List Representation
Linked List Operations
Linked List Algorithm
Program for Linked List in C++
This document discusses methods in object-oriented programming with C#. It defines methods as groups of statements that perform tasks and notes that every C# program has a Main method. It describes built-in methods provided by languages like Math methods and user-defined methods. It explains the syntax for defining methods, including access specifiers, return types, parameters, and bodies. It also covers passing arguments by value vs reference, and method overloading by having multiple methods with the same name but different parameters.
The document provides an overview of data structures and algorithms. It discusses key topics like:
1) Different types of data structures including primitive, linear, non-linear, and arrays.
2) The importance of algorithms and how to write them using steps, comments, variables, and control structures.
3) Common operations on data structures like insertion, deletion, searching, and sorting.
4) Different looping and selection statements that can be used in algorithms like for, while, and if-then-else.
5) How arrays can be used as a structure to store multiple values in a contiguous block of memory.
The document discusses various linear data structures like arrays, strings, stacks, queues, and linked lists. It provides details on representing single and multi-dimensional arrays, including addressing formulas. Operations on ordered lists like lists are defined. Linear lists using arrays are implemented with methods for adding, removing, and changing elements.
The document provides an overview and syllabus for a course on fundamentals of data structures. It covers topics such as linear and non-linear data structures including arrays, stacks, queues, linked lists, trees and graphs. It describes various data types in C like integers, floating-point numbers, characters and enumerated types. It also discusses operations on different data structures and analyzing algorithm complexity.
This document discusses lists as an abstract data type (ADT) and their implementation using arrays and linked lists. It defines a list as a finite, ordered sequence of elements and describes common list operations like insertion, deletion, traversal etc. Linked lists are introduced as an alternative implementation where each node contains a data field and link to the next node. The advantages of linked lists over arrays for dynamic data are also highlighted. Various real-world applications of lists are listed like implementing stacks, queues, graphs and dynamic memory allocation.
This document provides an overview of various data structures in R including vectors, lists, factors, matrices, and data frames. It discusses how to create, subset, and coerce between these structures. It also covers handling missing data and common data type conversions. The document recommends several books and online resources for learning more about R programming and statistics.
This document discusses tuples in Python. It begins by defining a tuple as a sequence of values that can be of any type and are indexed by integers. Tuples are immutable, like lists but values cannot be changed. Various tuple functions are described such as creating empty tuples, accessing tuple elements using indexes and loops, checking if an item exists, getting the length, and removing a tuple. Built-in tuple methods like count() and index() are explained. The key differences between tuples, lists, and dictionaries are outlined. Finally, some example programs demonstrating tuple operations are provided.
Sorting arranges elements in a list in a specified order. There are two categories of sorting: internal sorting, where all data fits in memory, and external sorting, where data exceeds memory. Common sorting algorithms include insertion sort and selection sort. Insertion sort iterates through a list and inserts each element in its sorted position, having O(n2) time complexity in worst case. Selection sort selects the minimum element and places it at the front on each pass, also with O(n2) worst case time complexity.
This document discusses hashing and related concepts:
- Hashing involves using a hash function to map keys to table indices in an array. Collisions occur when distinct keys hash to the same index.
- Collision resolution techniques include separate chaining, which stores keys that collide in a linked list at the index, and open addressing, which probes for the next empty slot when a collision occurs.
- Good hash functions aim to distribute keys uniformly among indices and avoid collisions. Properties like using the whole key and producing random-looking results are desirable.
- Hashing has applications beyond symbol tables, including data mining text and genomes by representing documents as vectors based on hashed subsequences.
The document discusses data structures and algorithms. It defines arrays as a series of objects of the same size and type, where each object is an element that can be accessed via an index. Algorithms are described as finite sequences of instructions to solve problems, with analysis of algorithms determining the resources like time and storage required.
This is a presentation on Arrays, one of the most important topics on Data Structures and algorithms. Anyone who is new to DSA or wants to have a theoretical understanding of the same can refer to it :D
The document discusses dynamic memory allocation and linked lists in C programming. It covers the key concepts of:
- Dynamic memory allocation functions like malloc(), calloc(), free(), and realloc() which are used to allocate and free memory during runtime.
- The differences between arrays and linked lists, with linked lists being a dynamic data structure that can grow and shrink in size more efficiently than arrays.
- How to create, traverse, insert, delete and perform other operations on singly and doubly linked lists using C pointers and memory allocation functions. Examples code is provided to demonstrate creating and manipulating linked lists.
The document discusses two standard template library containers for storing key-value pairs: unordered_map and map. Unordered_map uses a hash table to provide fast lookup of elements in average O(1) time, but the elements are in random order. Map uses a binary search tree to provide O(logN) lookup time and stores elements in sorted order. Both support insertion, erasure, and lookup of elements using similar functions but have different underlying implementations and time complexities.
Why you should care about functional programmingDhananjay Nene
The document discusses the benefits of functional programming including testability, easier integration, concurrency without locking, ability to leverage multicore processors, and brevity. It provides examples of functional programming concepts like higher order functions, pattern matching, and persistent data structures. While retraining the brain for a functional approach has an initial cost, the actual development costs are likely to be lower due to programs being smaller and cleaner with a focus on intent over implementation details.
An array is a collection of variables of the same type referenced by a common name. A structure groups variables of different types. An array of structures combines these concepts by creating an array where each element is a structure. For example, an array of fraction structures could be defined to hold multiple fractions. Each structure element in the array contains a numerator and denominator integer. The entire array of structures occupies a contiguous block of memory with each structure taking up the same amount of space. Individual structure elements can then be accessed using the array index and dot notation.
The document discusses data structures and lists in Python. It begins by defining data structures as a way to organize and store data for efficient access and modification. It then covers the different types of data structures, including primitive structures like integers and strings, and non-primitive structures like lists, tuples, and dictionaries. A large portion of the document focuses on lists in Python, describing how to perform common list manipulations like adding and removing elements using various methods. These methods include append(), insert(), remove(), pop(), and clear(). The document also discusses accessing list elements and other list operations such as sorting, counting, and reversing.
This document discusses various data structures in C#, including arrays, lists, queues, stacks, hash tables, and more. It provides code examples and explains the time complexity of common operations for each data structure. Asymptotic analysis and big-O notation are introduced for analyzing how efficiently a data structure handles operations as its size increases.
Data Structure Introduction
Data Structure Definition
Data Structure Types
Data Structure Characteristics
Need for Data Structure
Stack Definition
Stack Representation
Stack Operations
Stack Algorithm
Program for Stack in C++
Linked List Definition
Linked List Representation
Linked List Operations
Linked List Algorithm
Program for Linked List in C++
Linked List Defination
Linked List Representation
Linked List Operations
Linked List Algorithm
Program for Linked List in C++
This document discusses methods in object-oriented programming with C#. It defines methods as groups of statements that perform tasks and notes that every C# program has a Main method. It describes built-in methods provided by languages like Math methods and user-defined methods. It explains the syntax for defining methods, including access specifiers, return types, parameters, and bodies. It also covers passing arguments by value vs reference, and method overloading by having multiple methods with the same name but different parameters.
The document provides an overview of data structures and algorithms. It discusses key topics like:
1) Different types of data structures including primitive, linear, non-linear, and arrays.
2) The importance of algorithms and how to write them using steps, comments, variables, and control structures.
3) Common operations on data structures like insertion, deletion, searching, and sorting.
4) Different looping and selection statements that can be used in algorithms like for, while, and if-then-else.
5) How arrays can be used as a structure to store multiple values in a contiguous block of memory.
The document discusses various linear data structures like arrays, strings, stacks, queues, and linked lists. It provides details on representing single and multi-dimensional arrays, including addressing formulas. Operations on ordered lists like lists are defined. Linear lists using arrays are implemented with methods for adding, removing, and changing elements.
The document provides an overview and syllabus for a course on fundamentals of data structures. It covers topics such as linear and non-linear data structures including arrays, stacks, queues, linked lists, trees and graphs. It describes various data types in C like integers, floating-point numbers, characters and enumerated types. It also discusses operations on different data structures and analyzing algorithm complexity.
This document discusses lists as an abstract data type (ADT) and their implementation using arrays and linked lists. It defines a list as a finite, ordered sequence of elements and describes common list operations like insertion, deletion, traversal etc. Linked lists are introduced as an alternative implementation where each node contains a data field and link to the next node. The advantages of linked lists over arrays for dynamic data are also highlighted. Various real-world applications of lists are listed like implementing stacks, queues, graphs and dynamic memory allocation.
This document provides an overview of various data structures in R including vectors, lists, factors, matrices, and data frames. It discusses how to create, subset, and coerce between these structures. It also covers handling missing data and common data type conversions. The document recommends several books and online resources for learning more about R programming and statistics.
This document discusses tuples in Python. It begins by defining a tuple as a sequence of values that can be of any type and are indexed by integers. Tuples are immutable, like lists but values cannot be changed. Various tuple functions are described such as creating empty tuples, accessing tuple elements using indexes and loops, checking if an item exists, getting the length, and removing a tuple. Built-in tuple methods like count() and index() are explained. The key differences between tuples, lists, and dictionaries are outlined. Finally, some example programs demonstrating tuple operations are provided.
Sorting arranges elements in a list in a specified order. There are two categories of sorting: internal sorting, where all data fits in memory, and external sorting, where data exceeds memory. Common sorting algorithms include insertion sort and selection sort. Insertion sort iterates through a list and inserts each element in its sorted position, having O(n2) time complexity in worst case. Selection sort selects the minimum element and places it at the front on each pass, also with O(n2) worst case time complexity.
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.
The document discusses linear and binary search algorithms. Linear search is a sequential search where each element of a collection is checked sequentially to find a target value. Binary search improves on this by checking the middle element first and narrowing the search space in half each time based on the comparison. It allows searching sorted data more efficiently in logarithmic time as opposed to linear time for sequential search. The document provides pseudocode to implement binary search and an example to search an integer in a sorted array.
The document discusses algorithms and their use for solving problems expressed as a sequence of steps. It provides examples of common algorithms like sorting and searching arrays, and analyzing their time and space complexity. Specific sorting algorithms like bubble sort, insertion sort, and quick sort are explained with pseudocode examples. Permutations, combinations and variations as examples of combinatorial algorithms are also covered briefly.
One of the fundamental issues in computer science is ordering a list of items. Although there is a number of sorting algorithms, sorting problem has attracted a great deal of research, because efficient sorting is important to optimize the use of other algorithms. This paper presents a new sorting algorithm (Index Sort) which runs based on the previously sorted elements.. This algorithm was analyzed, implemented and tested and the results are promising for a random data.
The document discusses linear data structures using sequential organization. It begins by defining sequential access and linear data structures. Linear data structures traverse elements sequentially, with direct access to only one element. Examples given are arrays and linked lists. The document then focuses on arrays, providing definitions and discussing array representation in memory, basic array operations like traversal and searching, and multi-dimensional arrays. Two-dimensional and three-dimensional arrays are explained with examples.
The document discusses and compares several sorting algorithms: bubble sort, selection sort, insertion sort, merge sort, and quick sort. For each algorithm, it provides an explanation of how the algorithm works, pseudocode for the algorithm, and an analysis of the time complexity. The time complexities discussed are:
Bubble sort: O(N^2) in worst case, O(N) in best case
Selection sort: O(N^2)
Insertion sort: O(N^2) in worst case, O(N) in best case
Merge sort: O(N log N)
Quick sort: O(N log N) on average
This document provides an introduction and overview of arrays in C++. It defines what an array is, how to declare and initialize arrays, and how to access, insert, search, sort, and merge array elements. Key points covered include:
- An array is a sequenced collection of elements of the same data type. Elements are referenced using a subscript index.
- Arrays can be declared with a fixed or variable length. Elements are initialized sequentially in memory.
- Common array operations like accessing, inserting, searching, sorting and merging are demonstrated using for loops and examples. Searching techniques include sequential and binary search. Sorting techniques include selection, bubble and insertion sort.
- Arrays are passed
The document discusses various sorting algorithms including insertion sort, quicksort, merge sort, and their time complexities. Insertion sort has worst-case time complexity of O(n^2) but works well for small lists. Quicksort and merge sort have average time complexity of O(nlogn). Merge sort uses additional storage space while quicksort may have worst-case time of O(n^2) if the pivot choice is poor.
The document discusses various sorting algorithms including insertion sort, quicksort, merge sort, and their time complexities. Insertion sort has worst-case time complexity of O(n^2) but works well for small lists. Quicksort and merge sort have average time complexity of O(nlogn). Merge sort uses additional storage space while quicksort may have worst-case time of O(n^2) if the pivot choice is poor.
The document discusses various sorting algorithms including insertion sort, quicksort, merge sort, and their time complexities. Insertion sort has worst-case time complexity of O(n^2) but works well for small lists. Quicksort and merge sort have average time complexity of O(nlogn). Merge sort uses additional storage space while quicksort may have worst-case time of O(n^2) if the pivot choice is poor.
This is a seminar presentation on "SORTING" for Semester 2 exam at St. Xavier's College.The power point presenation deals with the requirement of sorting in our life,types of sorting techniques,code for implementing them,the time and space complexity of different sorting algorithms,the applications of sorting,its use in the industry and its future scope.The slide show contains .gif files which can't be seen here.For more details or any queries send me a mail at [email protected]
This chapter discusses searching and sorting algorithms. It covers sequential search, binary search, selection sort and insertion sort. Sequential search has linear time complexity while binary search has logarithmic time complexity, making it more efficient for large lists. Selection sort works by finding the minimum element and swapping it into place, taking on average n(n-1)/2 comparisons to sort a list of length n. Insertion sort iterates through the list and inserts each element into its sorted position, taking on average (n^2 + 3n - 4)/4 comparisons.
The document discusses various algorithms like priority queues, heaps, heap sort, merge sort, quick sort, binary search, and algorithms for finding the maximum and minimum elements in an array. It provides definitions and explanations of these algorithms along with code snippets and examples. Key steps of algorithms like heap sort, merge sort, and quick sort are outlined. Methods for implementing priority queues, binary search and finding max/min in optimal comparisons are also presented.
UNIT-1-PPT-Introduction about Power System Operation and ControlSridhar191373
Power scenario in Indian grid – National and Regional load dispatching centers –requirements of good power system - necessity of voltage and frequency regulation – real power vs frequency and reactive power vs voltage control loops - system load variation, load curves and basic concepts of load dispatching - load forecasting - Basics of speed governing mechanisms and modeling - speed load characteristics - regulation of two generators in parallel.
This presentation provides a comprehensive overview of air filter testing equipment and solutions based on ISO 5011, the globally recognized standard for performance testing of air cleaning devices used in internal combustion engines and compressors.
Key content includes:
Video Games and Artificial-Realities.pptxHadiBadri1
🕹️ #GameDevs, #AIteams, #DesignStudios — I’d love for you to check it out.
This is where play meets precision. Let’s break the fourth wall of slides, together.
Optimize Indoor Air Quality with Our Latest HVAC Air Filter Equipment Catalogue
Discover our complete range of high-performance HVAC air filtration solutions in this comprehensive catalogue. Designed for industrial, commercial, and residential applications, our equipment ensures superior air quality, energy efficiency, and compliance with international standards.
📘 What You'll Find Inside:
Detailed product specifications
High-efficiency particulate and gas phase filters
Custom filtration solutions
Application-specific recommendations
Maintenance and installation guidelines
Whether you're an HVAC engineer, facilities manager, or procurement specialist, this catalogue provides everything you need to select the right air filtration system for your needs.
🛠️ Cleaner Air Starts Here — Explore Our Finalized Catalogue Now!
UNIT-4-PPT UNIT COMMITMENT AND ECONOMIC DISPATCHSridhar191373
Statement of unit commitment problem-constraints: spinning reserve, thermal unit constraints, hydro constraints, fuel constraints and other constraints. Solution methods: priority list methods, forward dynamic programming approach. Numerical problems only in priority list method using full load average production cost. Statement of economic dispatch problem-cost of generation-incremental cost curve –co-ordination equations without loss and with loss- solution by direct method and lamda iteration method (No derivation of loss coefficients)
Better Builder Magazine brings together premium product manufactures and leading builders to create better differentiated homes and buildings that use less energy, save water and reduce our impact on the environment. The magazine is published four times a year.
ISO 4020-6.1 – Filter Cleanliness Test Rig: Precision Testing for Fuel Filter Integrity
Explore the design, functionality, and standards compliance of our advanced Filter Cleanliness Test Rig developed according to ISO 4020-6.1. This rig is engineered to evaluate fuel filter cleanliness levels with high accuracy and repeatability—critical for ensuring the performance and durability of fuel systems.
🔬 Inside This Presentation:
Overview of ISO 4020-6.1 testing protocols
Rig components and schematic layout
Test methodology and data acquisition
Applications in automotive and industrial filtration
Key benefits: accuracy, reliability, compliance
Perfect for R&D engineers, quality assurance teams, and lab technicians focused on filtration performance and standard compliance.
🛠️ Ensure Filter Cleanliness — Validate with Confidence.
This presentation provides a comprehensive overview of a specialized test rig designed in accordance with ISO 4548-7, the international standard for evaluating the vibration fatigue resistance of full-flow lubricating oil filters used in internal combustion engines.
Key features include:
2. INTRODUCTION
Sorting refers to arranging a set of data in a logical order.
Arrangement of the data in ascending or descending order.
Sorting is among most basic problem in algorithm design.
Can be done on names, numbers and records
Example: Telephone Directory ,Dictionary.
Being unique, phone number can work as a key to locate any record in the list.
4. The two main criterias to judge which
algorithm is better than the other have
been:
1)Time taken to sort the given data.
2)Memory Space required to do so.
SORTING EFFICIENCY
6. Done by comparing two
adjacent elements.
Simplest technique.
For n elements, n-1 pass
required.
BUBBLE SORTING
9. Conceptually simplest algo.
Finds smallest no and swaps with
element at first position.
Repeatedly selects the next smallest
no and swaps it into right place hence
the name.
SELECTION SORT
11. #include <stdio.h>
void swap(int *xp, int *yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}
void selectionSort(int arr[], int n)
{
int i, j, min_idx;
// One by one move boundary of uns/* Function to print an array */
orted subarray
for (i = 0; i < n-1; i++)
{
// Find the minimum element in unsorted array
min_idx = i;
for (j = i+1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;
// Swap the found minimum element with the first element
swap(&arr[min_idx], &arr[i]);
}
}
void printArray(int arr[], int size)
{
int i;
for (i=0; i < size; i++)
printf("%d ", arr[i]);
printf("n");
}
// Driver program to test above functions
int main()
{
int arr[] = {64, 25, 12, 22, 11};
int n = sizeof(arr)/sizeof(arr[0]);
selectionSort(arr, n);
printf("Sorted array: n");
printArray(arr, n);
return 0;
}
12. Efficient for smaller data.
Better than selection and bubble sort.
Space complexity less.
Stable sorting technique.
INSERTION SORT
14. void insertionSort(int arr[], int n)
{
int i, key, j;
for (i = 1; i < n; i++)
{
key = arr[i];
j = i-1;
/* Move elements of arr[0..i-1], that are
greater than key, to one position ahead
of their current position */
while (j >= 0 && arr[j] > key)
{
arr[j+1] = arr[j];
j = j-1;
}
arr[j+1] = key;
}
}
// A utility function to print an array of size n
void printArray(int arr[], int n)
{
int i;
for (i=0; i < n; i++)
printf("%d ", arr[i]);
printf("n");
}
/* Driver program to test insertion sort */
int main()
{
int arr[] = {12, 11, 13, 5, 6};
int n = sizeof(arr)/sizeof(arr[0]);
insertionSort(arr, n);
printArray(arr, n);
return 0;
}