Tuesday, December 18, 2018

Searching & Sorting




Sorting Algorithms

A Sorting Algorithm is used to rearrange a given array or list elements according to a comparison operator on the elements. The comparison operator is used to decide the new order of element in the respective data structure.
Bubble Sort

Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order.
Example:
First Pass:
5 1 4 2 8 ) –> ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps since 5 > 1.
( 1 5 4 2 8 ) –>  ( 1 4 5 2 8 ), Swap since 5 > 4
( 1 4 5 2 8 ) –>  ( 1 4 2 5 8 ), Swap since 5 > 2
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm does not swap them.
Second Pass:
1 4 2 5 8 ) –> ( 1 4 2 5 8 )
( 1 4 2 5 8 ) –> ( 1 2 4 5 8 ), Swap since 4 > 2
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –>  ( 1 2 4 5 8 )
Now, the array is already sorted, but our algorithm does not know if it is completed. The algorithm needs one whole pass without any swap to know it is sorted.
Third Pass:
1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )

Selection Sort
The selection sort algorithm sorts an array by repeatedly finding the minimum element (considering ascending order) from unsorted part and putting it at the beginning. The algorithm maintains two subarrays in a given array.

1) The subarray which is already sorted.
2) Remaining subarray which is unsorted.
In every iteration of selection sort, the minimum element (considering ascending order) from the unsorted subarray is picked and moved to the sorted subarray.
Insertion Sort

Insertion sort is a simple sorting algorithm that works the way we sort playing cards in our hands.

Example: 
insertion-sort
Quick Sort

 QuickSort is a Divide and Conquer algorithm. It picks an element as pivot and partitions the given array around the picked pivot. There are many different versions of quickSort that pick pivot in different ways.
  1. Always pick first element as pivot.
  2. Always pick last element as pivot (implemented below)
  3. Pick a random element as pivot.
  4. Pick median as pivot.
The key process in quickSort is partition(). Target of partitions is, given an array and an element x of array as pivot, put x at its correct position in sorted array and put all smaller elements (smaller than x) before x, and put all greater elements (greater than x) after x. All this should be done in linear time.
quicksort

Merge Sort

 Merge Sort is a Divide and Conquer algorithm. It divides input array in two halves, calls itself for the two halves and then merges the two sorted halves. The merge() function is used for merging two halves. The merge(arr, l, m, r) is key process that assumes that arr[l..m] and arr[m+1..r] are sorted and merges the two sorted sub-arrays into one. See following C implementation for details.
Merge-Sort-Tutorial

Searching Algorithms

Searching Algorithms are designed to check for an element or retrieve an element from any data structure where it is stored. Based on the type of search operation, these algorithms are generally classified into two categories:
  1. Sequential Search: In this, the list or array is traversed sequentially and every element is checked. For example: Linear Search.
  2. Interval Search: These algorithms are specifically designed for searching in sorted data-structures. These type of searching algorithms are much more efficient than Linear Search as they repeatedly target the center of the search structure and divide the search space in half. For Example: Binary Search.
Linear Search

 Linear search is a very simple search algorithm. In this type of search, a sequential search is made over all items one by one. Every item is checked and if a match is found then that particular item is returned, otherwise the search continues till the end of the data collection.
Image result for Linear search

Binary Search

Search a sorted array by repeatedly dividing the search interval in half. Begin with an interval covering the whole array. If the value of the search key is less than the item in the middle of the interval, narrow the interval to the lower half. Otherwise narrow it to the upper half. Repeatedly check until the value is found or the interval is empty.

binary-search1

Interpolation Search

Interpolation search is an improved variant of binary search. This search algorithm works on the probing position of the required value. For this algorithm to work properly, the data collection should be in a sorted form and equally distributed.

File Processing

Files and Streams


C views each file simply as a sequential stream of bytes. Each file ends either with an end-of-file markeror at a specific byte number recorded in a system-maintained, administrative data structure.
When a file is opened, a stream is associated with it.
treams provide communication channels between files and programs. Three files and their associated streams are automatically opened when program execution begins:
  • the standard input to read data from the keyboard
  • the standard output to print data on the screen.
  • the standard error

File Definition


file represents a sequence of bytes on the disk where a group of related data is stored. File is created for permanent storage of data. It is a ready made structure.
In C language, we use a structure pointer of file type to declare a file.

Opening and Closing Files


The fopen() function is used to create a new file or to open an existing file.
General Syntax:
*fp = FILE *fopen(const char *filename, const char *mode);
Here, *fp is the FILE pointer (FILE *fp), which will hold the reference to the opened(or created) file.
filename is the name of the file to be opened and mode specifies the purpose of opening the file. Mode can be of following types,
mode
description
r
opens a text file in reading mode
w
opens or create a text file in writing mode.
a
opens a text file in append mode
r+
opens a text file in both reading and writing mode
w+
opens a text file in both reading and writing mode
a+
opens a text file in both reading and writing mode
rb
opens a binary file in reading mode
wb
opens or create a binary file in writing mode
ab
opens a binary file in append mode
rb+
opens a binary file in both reading and writing mode
wb+
opens a binary file in both reading and writing mode
ab+
opens a binary file in both reading and writing mode

Closing a File

The fclose() function is used to close an already opened file.
General Syntax :
int fclose( FILE *fp);
Here fclose() function closes the file and returns zero on success, or EOF if there is an error in closing the file. This EOF is a constant defined in the header file stdio.h.


Structure & Union & Memory Allocation

Structure & Union

A structure is a user-defined data type available in C that allows to combining data items of different kinds. Structures are used to represent a record.
Defining a structure: To define a structure, you must use the struct statement. The struct statement defines a new data type, with more than one member.
A union is a special data type available in C that allows storing different data types in the same memory location. You can define a union with many members, but only one member can contain a value at any given time. Unions provide an efficient way of using the same memory location for multiple purposes.
Defining a Union: To define a union, you must use the union statement in the same way as you did while defining a structure. The union statement defines a new data type with more than one member for your program.
Similarities between Structure and Union
1.    Both are user-defined data types used to store data of different types as a single unit.
2.    Their members can be objects of any type, including other structures and unions or arrays. A member can also consist of a bit field.
3.    Both structures and unions support only assignment = and sizeof operators. The two structures or unions in the assignment must have the same members and member types.
4.    A structure or a union can be passed by value to functions and returned by value by functions. The argument must have the same type as the function parameter. A structure or union is passed by value just like a scalar variable as a corresponding parameter.
5.    ‘.’ operator is used for accessing members.



Memory Allocation

There are two types of allocation — static and dynamic.
Static Allocation means, that the memory for your variables is allocated when the program starts. The size is fixed when the program is created. It applies to global variables, file scope variables, and variables qualified with static defined inside functions.

Dynamic memory allocation is a bit different. You now control the exact size and the lifetime of these memory locations. If you don't free it, you'll run into memory leaks, which may cause your application to crash, since at some point of time, system cannot allocate more memory.


Function & Recursion

Modular Programming 

Modular programming is the process of subdividing a computer program into separate sub-programs.
A module is a separate software component. It can often be used in a variety of applications and functions with other components of the system. Similar functions are grouped in the same unit of programming code and separate functions are developed as separate units of code so that the code can be reused by other applications.
Object-oriented programming (OOP) is compatible with the modular programming concept to a large extent. Modular programming enables multiple programmers to divide up the work and debug pieces of the program independently.

The benefits of using modular programming include:
  • Less code has to be written.
  • A single procedure can be developed for reuse, eliminating the need to retype the code many times.
  • Programs can be designed more easily because a small team deals with only a small part of the entire code.
  • Modular programming allows many programmers to collaborate on the same application.
  • The code is stored across multiple files.
  • Code is short, simple and easy to understand.
  • Errors can easily be identified, as they are localized to a subroutine or function.
  • The same code can be used in many applications.
  • The scoping of variables can easily be controlled.

Function

A function is a set of statements that take inputs, do some specific computation and produces output.
The idea is to put some commonly or repeatedly done task together and make a function, so that instead of writing the same code again and again for different inputs, we can call the function.


Recursion

Recursion is the process of repeating items in a self-similar way. In programming languages, if a program allows you to call a function inside the same function, then it is called a recursive call of the function.

Although recursive code more concise it needs:
     More memory consumption – as stack memory is needed
     Takes longer time, should traverse through all recursive call using stack