Monday, December 17, 2018

SORTING

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.


•Sorting needs to speed up searching operation in a list.
•Sorting type:
–Ascending
–Descending
Sorting algorithm:
1. Internal sorting
    All data to be sorted are loaded to RAM
2. External sorting
    Sorting process using secondary storage

•Simple:

–   Bubble sort
–  Selection sort
–  Insertion sort
•Intermediate:
–   Quick Sort
–  Merge Sort

BUBBLE SORT

Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order.

•Compare two neighboring values.
•Compare and swap (if necessary)
•Also known as exchange sort
•Source Code of Bubble Sort:
void Bubble(int *DataArr, int n)
{
    int i, j;
    for(i=1; i<n; i++)
    for(j=n-1; j>=i; j--)
    if(DataArr[j-1] > DataArr[j])
               Swap(&DataArr[j-1],&DataArr[j]);
}






SELECTION SORT

Selection sort in C: C program for selection sort to sort numbers. This code implements selection sort algorithm to arrange numbers of an array in ascending order. With a little modification, it will arrange numbers in descending order.
Algorithm:
for(i=0; i<N-1; i++){      /* N=number of data */
  Set idx_smallest equal to i
  for(j=i+1; j<N; j++){
  If array[ j ] < array [ idx_smallest ] then idx_smallest = j
    }
  Swap array[ i ] with array[ idx_smallest ]
}



INSERTION SORT

Insertion sort is a simple sorting algorithm that works the way we sort playing cards in our hands.
Algorithm
// Sort an arr[] of size n
insertionSort(arr, n)
Loop from i = 1 to n-1.
……a) Pick element arr[i] and insert it into sorted sequence arr[0…i-1]




QUICK SORT


Like Merge 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.

Algorithm:
void QuickSort(int left, int right)
{
      if(left < right){
            //arrange elements  R[left],...,R[right] that
            //producing new sequence:
            R[left],...,R[J-1] < R[J] and R[J+1],...,R[right] > R[J].
            QuickSort(left, J-1);
            QuickSort(J+1, right);
       }
}







MERGE SORT


        Like QuickSort, 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.

•Merge Sort is a sorting algorithm based on the divide-and-conquer algorithm
•Divide-and-conquer is a general algorithm design paradigm
–Divide: divide the input data in two disjoint subsets
–Recur: solve the sub problems associated with subsets
–Conquer: combine the solutions for each subset into a solution




RECURSIVE

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.
void recursion() {
   recursion(); /* function calls itself */
}

int main() {
   recursion();
}
The C programming language supports recursion, i.e., a function to call itself. But while using recursion, programmers need to be careful to define an exit condition from the function, otherwise it will go into an infinite loop.
Recursive functions are very useful to solve many mathematical problems, such as calculating the factorial of a number, generating Fibonacci series, etc.

•Recursive is a function call inside a certain function calling itself
•Recursive Function, suitable for recursive problem
•Example :
 Factorial (n) or n! defined as follows :
 n! = 1, for n = 0;
 n! = n * (n-1)!, for n > 0
 4! = 4 * 3!
 3! = 3 * 2!
 2! = 2 * 1!
 1! =  1* 0!
 0! =  1
 Trace back : 4! = 1*2*3*4 = 24



Recursive Function has two components:
–Base case:
  return value(constant) without calling next recursive call.
–Reduction step:
  sequence of input value converging to the base case.
Example: (Factorial function)
–Base case : n = 0
–Reduction step: f(n) = n * f(n-1)


Example: (Iterative vs Recursive)

1.


Number Factorial

       The following example calculates the factorial of a given number using a recursive function −
#include <stdio.h>

unsigned long long int factorial(unsigned int i) {

   if(i <= 1) {
      return 1;
   }
   return i * factorial(i - 1);
}

int  main() {
   int i = 12;
   printf("Factorial of %d is %d\n", i, factorial(i));
   return 0;
}
When the above code is compiled and executed, it produces the following result −
Factorial of 12 is 479001600

2.


Fibonacci Series

The following example generates the Fibonacci series for a given number using a recursive function −
#include <stdio.h>

int fibonacci(int i) {

   if(i == 0) {
      return 0;
   }
 
   if(i == 1) {
      return 1;
   }
   return fibonacci(i-1) + fibonacci(i-2);
}

int  main() {

   int i;
 
   for (i = 0; i < 10; i++) {
      printf("%d\t\n", fibonacci(i));
   }
 
   return 0;
}
When the above code is compiled and executed, it produces the following result −
0 
1 
1 
2 
3 
5 
8 
13 
21 
34



Recursive Drawback
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
Recursive Best Practice
Generally, use recursive solution if:
–Difficult to solve iteratively.
–Efficiency using recursive has been reached
–Efficiency is less important in comparison with readability
–Memory efficiency and execution time are not the main concern
Consider carefully speed and efficiency using iterative approach, rather than nice logical design using recursive



Fibonacci Number
sequence: 0, 1, 1, 2, 3, 5, 8, 13 ...
Relation between the number define recursively as follows:
Fib(N) = N           if N = 0 or 1
Fib(N) = Fib(N-2) + Fib(N-1)   if N >= 2



int Fib(int n) {
   int f;
   if(n==0) f = 0;
      else if(n==1) f = 1;
         else f = Fib(n-2) + Fib(n-1);
   return f;
}