Data structures and algorithm tutorial

Thursday, September 10, 2020

Bucket Sort Algorithm and Bucket Sorting program in c

September 10, 2020 0
Bucket Sort Algorithm and Bucket Sorting program in c
In this tutorial, you'll find out how the bucket sort algorithm works. additionally, you'll find functional samples of bucket sorting by compartment in C, C ++, Java, and Python.

Bucket Sort may be a sorting technique that sorts items by first dividing the things into several groups called buckets. Items inside each bucket are sorted using one among the acceptable sorting algorithms or by recursively calling an equivalent algorithm.

Several buckets are created. Each bucket is crammed with a selected range of things. Items inside the bucket are sorted using the other algorithm. Finally, the weather of the bucket is gathered to urge the sorted array.

The bucket sorting process is often understood as a dispersal approach. the things are first dispersed in buckets then the things within the buckets are sorted. Finally, the weather is put together so as.

 

How does the Bucket Sort Algorithm work?

  •  Suppose the input array is:
Bucket Sort Algorithm
Bucket Sort Algorithm

Create an array of size 10. Each location during this array is employed as a bucket to store items.
 
algorithm for bucket sort
algorithm for bucket sort

  • Insert items into buckets from the array. the weather are inserted consistent with the reach of the bucket.
Bucket sort
Bucket sort

  • In our code example, we've compartments each of which matches from 0 to 1, 1 to 2, 2 to 3, ...... (n-1) to n.
  • Suppose an input element of .23 is taken. it's multiplied by the dimensions = 10 (i.e. .23 * 10 = 2.3). Then, it's converted to an integer (i.e. 2.3≈2). Finally, .23 is inserted into bucket-2.

Likewise, .25 is additionally inserted within the same bucket. Each time, the ground value of the floating-point number is taken.

If we take whole numbers as input, we'd like to divide it by the interval (10 here) to urge the ground value.

Likewise, other items are inserted into their respective buckets.
sorting algorithms in c
sorting algorithms
  • Items in each compartment are sorted using one among the stable sorting algorithms. Here we've used quicksort (built-in function).

bucket sort in c
bucket sort in c


  • The elements of every bucket are put together.
This is done by iterating through the bucket and inserting a private element into the first array on each cycle. The item within the compartment is deleted when it's copied to the first table.

bucket sort algorithm
bucket sort algorithm

bucket sort complexity



  •  Worst-case complexity: O (n2)
 When there are proximity items within the array, they're likely to be placed within the same compartment. this might end in some compartments containing more items than others.
 This makes the complexity of the algorithm wont to sort the things within the bucket depend.
 The complexity gets even worse when the weather are in reverse order. If insertion sort is employed to sort the things within the bucket, the time complexity becomes O (n2).

  •  Best case complexity: O (n + k)
 This happens when the things are evenly distributed within the buckets with an almost equal number of things in each bucket.
 The complexity becomes even better if the things inside the buckets are already sorted.
 If insert sort is employed to sort items during a bucket, the general complexity at the best is going to be linear, ie. O (n + k). O (n) is that the complexity for creating the buckets and O (k) is that the complexity for sorting the weather of the bucket using algorithms with linear time complexity at the best.

  •  Average complexity of cases: O (n)
 This happens when the weather is distributed randomly within the array. albeit the things aren't distributed evenly, sorting by the bucket is performed in linear time. This remains true until the sum of the squares of the compartment sizes is linear within the total number of elements.

Bucket Sort Algorithm

Bucket Sort Algorithm
Bucket Sort Algorithm

Bucket sort program in c programming

#include<stdio.h>
#include<stdlib.h> 

#define NARRAY 7   
#define NBUCKET 6  
#define INTERVAL 10  

struct Node {
  int data;
  struct Node *next;
};

void BucketSort(int arr[]);
struct Node *InsertionSort(struct Node *list);
void print(int arr[]);
void printBuckets(struct Node *list);
int getBucketIndex(int value);

// Sorting function
void BucketSort(int arr[]) {
  int i, j;
  struct Node **buckets;

  // Create buckets and allocate memory size
  buckets = (struct Node **)malloc(sizeof(struct Node *) * NBUCKET);

  // Initialize empty buckets
  for (i = 0; i < NBUCKET; ++i) {
    buckets[i] = NULL;
  }

  // Fill the buckets with respective elements
  for (i = 0; i < NARRAY; ++i) {
    struct Node *current;
    int pos = getBucketIndex(arr[i]);
    current = (struct Node *)malloc(sizeof(struct Node));
    current->data = arr[i];
    current->next = buckets[pos];
    buckets[pos] = current;
  }

  // Print the buckets along with their elements
  for (i = 0; i < NBUCKET; i++) {
    printf("Bucket[%d]: ", i);
    printBuckets(buckets[i]);
    printf("\n");
  }

  // Sort the elements of each bucket
  for (i = 0; i < NBUCKET; ++i) {
    buckets[i] = InsertionSort(buckets[i]);
  }

  printf("-------------\n");
  printf("Bucktets after sorting\n");
  for (i = 0; i < NBUCKET; i++) {
    printf("Bucket[%d]: ", i);
    printBuckets(buckets[i]);
    printf("\n");
  }

  // Put sorted elements on arr
  for (j = 0, i = 0; i < NBUCKET; ++i) {
    struct Node *node;
    node = buckets[i];
    while (node) {
      arr[j++] = node->data;
      node = node->next;
    }
  }

  return;
}

// Function to sort the elements of each bucket
struct Node *InsertionSort(struct Node *list) {
  struct Node *k, *nodeList;
  if (list == 0 || list->next == 0) {
    return list;
  }

  nodeList = list;
  k = list->next;
  nodeList->next = 0;
  while (k != 0) {
    struct Node *ptr;
    if (nodeList->data > k->data) {
      struct Node *tmp;
      tmp = k;
      k = k->next;
      tmp->next = nodeList;
      nodeList = tmp;
      continue;
    }

    for (ptr = nodeList; ptr->next != 0; ptr = ptr->next) {
      if (ptr->next->data > k->data)
        break;
    }

    if (ptr->next != 0) {
      struct Node *tmp;
      tmp = k;
      k = k->next;
      tmp->next = ptr->next;
      ptr->next = tmp;
      continue;
    } else {
      ptr->next = k;
      k = k->next;
      ptr->next->next = 0;
      continue;
    }
  }
  return nodeList;
}

int getBucketIndex(int value) {
  return value / INTERVAL;
}

void print(int ar[]) {
  int i;
  for (i = 0; i < NARRAY; ++i) {
    printf("%d ", ar[i]);
  }
  printf("\n");
}

// Print buckets
void printBuckets(struct Node *list) {
  struct Node *cur = list;
  while (cur) {
    printf("%d ", cur->data);
    cur = cur->next;
  }
}

// Driver code
int main(void) {
  int array[NARRAY] = {42, 32, 33, 52, 37, 47, 51};

  printf("Initial array: ");
  print(array);
  printf("-------------\n");

  BucketSort(array);
  printf("-------------\n");
  printf("Sorted array: ");
  print(array);
  return 0;
}

Applications For the Bucket sort Algorithm

  •  the entry is evenly distributed over a variety.
     there are floating-point values

Count sort algorithm and it's exampels

September 10, 2020 0
Count sort algorithm and it's exampels
In this tutorial, you'll find out how to count sort algorithm works. you'll also find practical samples of count sort in C, C ++, Java, and Python.

Count sorting may be an algorithm that sorts the weather of an array by counting the number of occurrences of every unique element within the array. The count is stored in an auxiliary array and sorting is completed by mapping the count as an index of the auxiliary array.
 

How does the count sort Algorithm work?



  •  Find the utmost element (be it max) from the given array.
counting sort in c
counting sort in c


  • Initialize an array of max length + 1 with all 0 elements. This array is employed to store the number of elements within the array.
count sort algorithm
count sort algorithm


  • Store the amount of every element at their respective index within the count array
count sort algorithm
count sort algorithm

For example: if the count of element 3 is 2 then, 2 is stored within the 3rd position of the count table. If element "5" isn't present within the array, then 0 is stored in the 5th position.

  • Store the cumulative sum of things within the count array. This helps to put the weather within the correct index of the sorted array.
counting sort
counting sort


  • Find the index of every element within the original array within the count array. this provides the cumulative count. Place the element at the calculated index as shown within the figure below.
counting sort algorithm in c programming
counting sort algorithm in c programming

  • After placing each item in its correct position, decrease its number by one

Counting Sort Algorithm


Counting Sort Algorithm
Counting Sort Algorithm


C Program For Counting Sort Algorithm



// Counting sort in C programming

#include <stdio.h>

void countingSort(int array[], int size) {
  int output[10];

  // Find the largest element of the array
  int max = array[0];
  for (int i = 1; i < size; i++) {
    if (array[i] > max)
      max = array[i];
  }

  int count[10];

  // Initialize count array with all zeros.
  for (int i = 0; i <= max; ++i) {
    count[i] = 0;
  }

  // Store the count of each element
  for (int i = 0; i < size; i++) {
    count[array[i]]++;
  }

  for (int i = 1; i <= max; i++) {
    count[i] += count[i - 1];
  }


  for (int i = size - 1; i >= 0; i--) {
    output[count[array[i]] - 1] = array[i];
    count[array[i]]--;
  }

 
  for (int i = 0; i < size; i++) {
    array[i] = output[i];
  }
}

void printArray(int array[], int size) {
  for (int i = 0; i < size; ++i) {
    printf("%d  ", array[i]);
  }
  printf("\n");
}


int main() {
  int array[] = {4, 2, 2, 8, 3, 3, 1};
  int n = sizeof(array) / sizeof(array[0]);
  countingSort(array, n);
  printArray(array, n);
}

counting sort of time complexity


Time complexities:

There are mainly four main loops. (The look for the most important value are often done outside of the function.)

Overall complexity = O (max) + O (size) + O (max) + O (size) = O (max + size)
  •  Worst case complexity: O (n + k)
  •  Best case complexity: O (n + k)
  •  Average complexity of cases: O (n + k)

In all of the above cases, the complexity is that the same because regardless of how the weather is placed within the array, the algorithm goes through n + k times.

There is no comparison between items, so it's better than comparison based sorting techniques. But, it's bad if the integers are very large because the array of that size must be created.

Space complexity For counting sort algorithm:

The spatial complexity of count sorting is O (max). The greater the range of elements, the greater the complexity of the space.

Counting sorting Applications

  •  there are smaller integers with multiple counts.
  •  linear complexity is the need.

Thursday, July 23, 2020

What Is Quicksort Algorithm with Program in C programming

July 23, 2020 0
What Is Quicksort Algorithm with Program in C programming
In this tutorial, you'll find out how Quicksort Algorithm works. Also, you'll find working samples of Quicksort Algorithm in C, C++ Python, and Java.

Quicksort is an algorithm supported divide and conquer approach during which the array is split into subarrays and these sub-arrays is recursively called to sort the weather.

How the QuickSort Algorithm Works?

  •  A pivot element is chosen from the array. you'll choose any element from the array because of the pivot element. Here, we've taken the rightmost (ie. the last element) of the array because of the pivot element.

Quick Sort Steps
Select a pivot element in Quicksort

 

  • The elements smaller than the pivot element are placed on the left and therefore the elements greater than the pivot element are placed on the proper.
Quick Sort Steps
put the greater element in right and other in left

 
The above arrangement is achieved by the subsequent steps.
  •  A pointer is fixed at the pivot element. The pivot element is compared with the weather beginning from the primary index. If the element greater than the pivot element is reached, a second pointer is about for that element.
  •  Now, the pivot element is compared with the opposite elements (a third pointer). If a component smaller than the pivot element is reached, the smaller element is swapped with the greater element found earlier.

Quick Sort Steps
compare the element for the quicksort sorting algorithm

 

  • The process goes on until the second last element is reached.
After following the process, the pivot element in Quicksort Algorithm is swapped with the second pointer.

Quick Sort Steps
Swap pivot element with the second pointer for sorting algorithm

 Now the left and right subparts of this pivot element are taken for further processing within the steps below.

  • Pivot elements are again chosen for the left and therefore the right sub-parts separately. With the help of these sub-parts, the chosen pivot elements are placed in their right position. Then, step 2 is repeated.

Quick Sort Steps
Select pivot element in Quicksort algorithm of in each half and put at the correct place using recursion

 

  • The sub-parts are again divided into smaller sub-parts until each subpart is made of one element.
  • At now, the array is already sorted.

Check For Quick Sort Algorithm:-

Check For Quick Sort Algorithm
Check For Quick Sort Algorithm

Quicksort algorithm Program In C 

#include <stdio.h>

// check out the Function to swap position of elements in quicksort algorithm
void swap(int *a, int *b) {
  int t = *a;
  *a = *b;
  *b = t;
}

// Function to partition for the quick sort algorithm array on the basis of pivot element
int partition(int array[], int low, int high) {
  
  // Now Select the pivot element
  int pivot = array[high];
  int i = (low - 1);

  // comparison for element Put the elements smaller than pivot on the left 
  // and put the greater element than pivot on the right of pivot
  for (int j = low; j < high; j++) {
    if (array[j] <= pivot) {
      i++;
      swap(&array[i], &array[j]);
    }
  }

  swap(&array[i + 1], &array[high]);
  return (i + 1);
}

void quickSort(int array[], int low, int high) {
  if (low < high) {
    
   
    int pi = partition(array, low, high);
    
    // Sort the elements on the left of the pivot
    quickSort(array, low, pi - 1);
    
    // Sort the elements on the right of pivot
    quickSort(array, pi + 1, high);
  }
}

// Function to print eklements of an array in quicksort
void printArray(int array[], int size) {
  for (int i = 0; i < size; ++i) {
    printf("%d  ", array[i]);
  }
  printf("\n");
}

// Driver code
int main() {
  int data[] = {8, 7, 2, 1, 0, 9, 6};
  int n = sizeof(data) / sizeof(data[0]);
  quickSort(data, 0, n - 1);
  printf("Sorted array in ascending order: \n");
  printArray(data, n);
}

Quicksort Algorithm uses recursion for sorting the sub-parts.

On the idea of Divide and conquer approach, the quicksort algorithm is often explained as:
  •  Divide
 The array is split into subparts taking pivot because of the partitioning point. the weather smaller than the pivot is placed to the left of the pivot and therefore the elements greater than the pivot are placed to the proper.


  •  Conquer

 The left and therefore the right subparts are again partitioned using the by selecting pivot elements for them. this will be achieved by recursively passing the subparts into the QuickSorting algorithm.
 

  • Combine

 This step doesn't play a big role in quicksort. The array is already sorted at the top of the conquer step.

You can understand the working of quicksort with the assistance of the illustrations below.


Quick Sort Steps
Sorting the left side elements by recursion

 

Quick Sort Steps
Sorting the right side elements by recursion

 

Complexity For Quicksort Algorithm

  • Time Complexities

 Worst Case Complexity [Big-O]: O(n2)
 

 It occurs when the pivot element picked is either the best or the littlest element.

 This condition results in the case during which the pivot element lies in an extreme end of the sorted array. One sub-array is usually empty and another sub-array contains n - 1 element. Thus, the quicksort Algorithm is named only on this sub-array.


 However, the Quicksort algorithm in C and for any other languages has better performance for scattered pivots.


 Best Case Complexity [Big-omega]: O(n*log n)


 It occurs when the pivot element is usually the central element or almost the center element.


 Average Case Complexity [Big-theta]: O(n*log n)
 

It occurs when the above conditions don't occur.
  • Space Complexity For Quicksort Algorithm

The space complexity for quicksort is O(log n).


Quicksort Applications

Quicksort Algorithm is implemented when

  •  the programing language is sweet for recursion
  •  time complexity matters
  •  space complexity matters

Monday, July 20, 2020

selection sort algorithm and selection sort Time Complexities

July 20, 2020 0
selection sort algorithm and selection sort Time Complexities
In this tutorial, you'll find out how the selection sort algorithm works. Also, you'll find working samples of selection sort in C, C++, Java, and Python.

Selection sort is an algorithm that selects the littlest element from an unsorted list in each iteration and places that element at the start of the unsorted list.

Learn How the Selection Sort Works

  •  Set the primary element as a minimum.
Selection Sort Steps
check the first minimum number

  • Compare minimum with the second element. If the second number is smaller than minimum, so assign the second number as minimum in the selection sort algorithm.

    Compare
    minimum with the third element. Again, if the third number is smaller, then assign minimum to the third number in the selection sort algorithm or do nothing. the method goes on until the last element. 


Selection Sort Steps
Compare the number with the remaining number


 

  • After each iteration, minimum is placed within the front of the unsorted list.

Selection Sort Steps
Swap the first number with the minimum in sorting algorithm


 

  • For each iteration, indexing starts from the primary unsorted element. Step 1 to three are repeated until all the weather are placed at their correct positions.

Selection Sort Steps
step - 0 for sorting



 
Selection sort steps
step - 1 for sorting
 
Selection sort steps
step - 2 for sorting
 
Selection sort steps
step - 3 for sorting


 

 Algorithm For Selection Sort


selectionSort(array, size)
 repeat (size - 1) times
 set the primary unsorted element because the minimum
 for every of the unsorted elements
 if element < currentMinimum
 set element as new minimum
 swap minimum with first unsorted position
end selectionSort

Number of comparisons: (n - 1) + (n - 2) + (n - 3) + ..... + 1 = n(n - 1) / 2 nearly equals to n2.

Complexity for selection sort algorithm = O(n2)

Also, we will analyze the complexity by simply observing the number of loops. There are 2 loops therefore the complexity is n*n = n2.

Time Complexities:

Time Complexities Selection Sort Algorithm
Time Complexities Selection Sort Algorithm


  •  Worst Case Complexity: O(n2)
 If we would like to sort in ascending order and therefore the array is in descending order then, the worst case occurs.


  •  Best Case Complexity: O(n2)
 It occurs when the array is already sorted


  •  Average Case Complexity: O(n2)
 It occurs when the weather of the array are in jumbled order (neither ascending nor descending).

The time complexity of the choice sort is that the same altogether cases. At every step, you've got to seek out the minimum element and put it within the right place. The minimum element isn't known until the top of the array isn't reached.

Space Complexity:


Space complexity is O(1) because an additional variable temp is employed.

  • Selection Sort Applications

The selection sort is employed when:
  •  a little list is to be sorted
  •  cost of swapping doesn't matter
  •  checking of all the weather is compulsory
  •  cost of writing to a memory matter like in non-volatile storage (number of writes/swaps is O(n) as compared to O(n2) of bubble sort)

Wednesday, July 15, 2020

Merge Sort Algorithm in data structure and algorithm with Merge Sort program

July 15, 2020 0
Merge Sort Algorithm in data structure and algorithm with Merge Sort program
In this tutorial, you'll study merge sort. Also, you'll find working samples of merge sort algorithm in C, C++, Java, and Python.

Merge Sort may be a quite Divide and Conquer algorithm in programming. it's one of the foremost popular sorting algorithms and an excellent thanks to developing confidence in building recursive algorithms.

Divide and Conquer Strategy for merge sort algorithm


Using the Divide and Conquer technique, we divide a drag into subproblems. When the answer to every subproblem is prepared, we 'combine' the results from the subproblems to unravel the most problem.

Suppose we had to sort an array A. So we divide this array into subproblems which start at index p and ending at index r, denoted as A[p..r].

Divide
If q is that the half-way point between p and r, then we will split the subarray A[p..r] into two arrays A[p..q] and A[q+1, r].

Conquer
In the conquer step, we attempt to sort both the subarrays A[p..q] and A[q+1, r]. If we've not yet reached the bottom case, we again divide both these subarrays and check out to sort them.

Combine
When the conquer step reaches the bottom step and that we get two sorted subarrays A[p..q] and A[q+1, r] for array A[p..r], we combine the results by creating a sorted array A[p..r] from two sorted subarrays A[p..q] and A[q+1, r].

The MergeSort Algorithm


The MergeSort function repeatedly divides the array into two halves until we reach a stage where we attempt to perform MergeSort on a subarray of size 1 i.e. p == r.

 

After that, the merge function comes into play and combines the sorted arrays into larger arrays until the entire array is merged.


MergeSort(A, p, r):
 if p > r 
 return
 q = (p+r)/2
 mergeSort(A, p, q)
 mergeSort(A, q+1, r)
 merge(A, p, q, r)

To sort a whole array, we'd like to call MergeSort(A, 0, length(A)-1).

As shown within the image below, the merge sort algorithm recursively divides the array into halves until we reach the bottom case of array with 1 element. then, the merge function picks up the sorted sub-arrays and merges them to gradually sort the whole array.


merge sort algorithm
merge sort algorithm


The merge Step of Merge Sort algorithm


Every recursive algorithm depends on a base case and therefore the ability to mix the results from base cases. Merge sort is not any different. the foremost important part of the merge sort algorithm is, you guessed it, merge step.

The merge step is that the solution to the straightforward problem of merging two sorted lists(arrays) to create one large sorted list(array).

The algorithm maintains three-pointers, one for every one of the 2 arrays and one for maintaining the present index of the ultimate sorted array.


Have we reached the top of any of the arrays?
 No:
 Compare current elements of both arrays
 Copy smaller element into a sorted array
 Move pointer of the element containing smaller element
 Yes:
 Copy all remaining elements of a non-empty array


merge sort algorithm steps
merge sort algorithm steps

Writing the Code for Merge Algorithm


A noticeable difference between the merging step we described above and therefore the one we use for merge sort is that we only perform the merge function on consecutive sub-arrays.

This is why we only need the array, the primary position, the last index of the primary subarray(we can calculate the primary index of the second subarray), and therefore the last index of the second subarray.

Our task is to merge two subarrays A[p..q] and A[q+1..r] to make a sorted array A[p..r]. therefore the inputs to the function are A, p, q and r

The merge function works as follows:

  •  Create copies of the subarrays L ← A[p..q] and M ← A[q+1..r].
  •  Create three-pointers i, j and k
         a.  I maintain a current index of L, starting at 1
         b.  j maintains a current index of M, starting at 1
         c. k maintains the present index of A[p..q], starting at p.

  •  Until we reach the top of either L or M, pick the larger among the weather from L and M and place them within the correct position at A[p..q]
  •  once we run out of elements in either L or M, devour the remaining elements and put in A[p..q]

In code, this is able to look like:

// Merge two subarrays L and M into arr
void merge(int arr[], int p, int q, int r) {

 // Create L ← A[p..q] and M ← A[q+1..r]
 int n1 = q - p + 1;
 int n2 = r - q;

 int L[n1], M[n2];

 for (int i = 0; i < n1; i++)
 L[i] = arr[p + i];
 for (int j = 0; j < n2; j++)
 M[j] = arr[q + 1 + j];

 // Handle the current index of sub-arrays and main array
 int i, j, k;
 i = 0;
 j = 0;
 k = p;

 // follow these steps until we reach either end of either L or M, pick larger among
 // elements L and M and place them within the correct position at A[p..r]
 while (i < n1 && j < n2) {
 if (L[i] <= M[j]) {
            arr[k] = L[i];
            i++;
        } else {
            arr[k] = M[j];
            j++;
        }
        k++;
    }

    // When all the elements are end in either L or M,
    // then take the remaining elements and put in A[p..r]
    while (i < n1) {
        arr[k] = L[i];
        i++;
        k++;
    }

    while (j < n2) {
        arr[k] = M[j];
        j++;
        k++;
    }
}

Merge( ) Function Explained Step-By-Step


A lot is occurring during this function, so let's take an example to ascertain how this is able to work.

As usual, an image speaks a thousand words.


margesort algorithm
mergesort algorithm

The array A[0..5] contains two sorted subarrays A[0..3] and A[4..5]. allow us to see how the merge function will merge the 2 arrays.
void merge(int arr[], int p, int q, int r) {
// Here, p = 0, q = 4, r = 5 (size of array)

Step 1: Create duplicate copies of sub-arrays to be sorted

// Create L ← A[p..q] and M ← A[q+1..r]
 int n1 = q - p + 1 = 3 - 0 + 1 = 4;
 int n2 = r - q = 5 - 3 = 2;

 int L[4], M[2];

 for (int i = 0; i < 4; i++)
 L[i] = arr[p + i];
 // L[0,1,2,3] = A[0,1,2,3] = [1,5,10,12]

 for (int j = 0; j < 2; j++)
 M[j] = arr[q + 1 + j];
 // M[0,1,2,3] = A[4,5] = [6,9] 
mergesort algorithm
mergesort algorithm


Step 2: Maintain a current index of sub-arrays and the main array
maintain copy of sub-array
maintain copies of sub-array

Step 3: Until we reach the top of either L or M, pick larger among elements L and M and place them within the correct position at A[p..r]
  while (i < n1 && j < n2) { 
        if (L[i] <= M[j]) { 
            arr[k] = L[i]; i++; 
        } 
        else { 
            arr[k] = M[j]; 
            j++; 
        } 
        k++; 
    }
mergesort algorithm
mergesort algorithm

 

Step 4: once we run out of elements in either L or M, devour the remaining elements and put in A[p..r]
while (i < n1)
    {
        arr[k] = L[i];
        i++;
        k++;
    }

Copy the remaining elements in merge sort algorithm
Copy the remaining elements

    while (j < n2)
    {
        arr[k] = M[j];
        j++;
        k++;
    }
}

mergesort in c
mergesort in c


This step would are needed if the dimensions of M were greater than L.

At the top of the merge function, the subarray A[p..r] is sorted.



Merge sort program in c: - 

// Merge sort in C

#include 

// Merge two subarrays L and M into arr
void merge(int arr[], int p, int q, int r) {

  // Create L ← A[p..q] and M ← A[q+1..r]
  int n1 = q - p + 1;
  int n2 = r - q;

  int L[n1], M[n2];

  for (int i = 0; i < n1; i++)
    L[i] = arr[p + i];
  for (int j = 0; j < n2; j++)
    M[j] = arr[q + 1 + j];

  // Maintain current index of sub-arrays and main array
  int i, j, k;
  i = 0;
  j = 0;
  k = p;

  // Until we reach either end of either L or M, pick larger among
  // elements L and M and place them in the correct position at A[p..r]
  while (i < n1 && j < n2) {
    if (L[i] <= M[j]) {
      arr[k] = L[i];
      i++;
    } else {
      arr[k] = M[j];
      j++;
    }
    k++;
  }

  // When we run out of elements in either L or M,
  // pick up the remaining elements and put in A[p..r]
  while (i < n1) {
    arr[k] = L[i];
    i++;
    k++;
  }

  while (j < n2) {
    arr[k] = M[j];
    j++;
    k++;
  }
}

// Divide the array into two subarrays, sort them and merge them
void mergeSort(int arr[], int l, int r) {
  if (l < r) {

    // m is the point where the array is divided into two subarrays
    int m = l + (r - l) / 2;

    mergeSort(arr, l, m);
    mergeSort(arr, m + 1, r);

    // Merge the sorted subarrays
    merge(arr, l, m, r);
  }
}

// Print the array
void printArray(int arr[], int size) {
  for (int i = 0; i < size; i++)
    printf("%d ", arr[i]);
  printf("\n");
}

// Driver program
int main() {
  int arr[] = {6, 5, 12, 10, 9, 1};
  int size = sizeof(arr) / sizeof(arr[0]);

  mergeSort(arr, 0, size - 1);

  printf("Sorted array: \n");
  printArray(arr, size);
}



Merge Sort Complexity

Time Complexity
  • Best Case Complexity: O(n*log n)
  • Worst Case Complexity: O(n*log n)
  • Average Case Complexity: O(n*log n)

  • Space Complexity

The space complexity of merge sort is O(n).



  • Merge Sort Applications


  •  Inversion count problem
  •  External sorting
  •  E-commerce applications

Saturday, July 11, 2020

insertion sort algorithm with example in c for data structure algorithm

July 11, 2020 0
 insertion sort algorithm with example in c for data structure algorithm
In this tutorial, you'll find out how the Insertion sort algorithm works. Also, you'll find working samples of insertion sort in C, C++, Java, and Python.

Insertion sort algorithm works similarly as we sort cards in our hands during cards.

Insertion sort algorithm with example
Insertion sort algorithm

We assume that the primary card is already sorted then, we select an unsorted card. If the unsorted card is bigger than the cardboard in hand, it's placed on the proper otherwise, to the left. within the same way, other unsorted cards are taken and put at their right place.

A similar approach is employed by insertion sort.

Learn How the Insertion Sort algorithm is going to Works


Insertion sort may be an algorithm that places an unsorted element at its suitable place in each iteration.


Initial array in insertion sort
Initial array in insertion sort




The first element within the array is assumed to be sorted. Now Take the second element and work with it and store it separately in key.

in this photo first element greater then key is  in insertion sort
in this photo first element greater then key is  in insertion sort

If the first element is greater than key, then key is placed in front of the first element 

Compare key with the primary element. If the primary element is bigger than key, then key's placed ahead of the primary element.

Now, the primary two elements are sorted.

Take the third element and compare it with the weather on the left of it. Placed it just behind the element smaller than it. If there's no element smaller than it, then place it at the start of the array. 


Insertion Sort algorithm'
insertion sort algorithm step 1

follow these steps and put every unsorted element at its right position 




insertion sort algorithm step3
insertion sort algorithm step 2



 
 
Insertion Sort Steps 3
in step 3 behind 1, all array is sorted



 



Algorithm for Insertion Sort:-


insertionSort(array)
 mark first element as sorted
 for every unsorted element X
 'extract' the element X
 for j X
 move sorted element to the proper by 1
 break loop and insert X here
end insertionSort

Complexity:-

Time Complexities


 Worst Case Complexity: O(n2)
 Suppose, an array is in ascending order, and you would like to sort it in descending order. during this case, the worst-case complexity occurs.

 Each element has got to be compared with each of the opposite elements so, for each nth element, (n-1) number of comparisons are made.

 Thus, the entire number of comparisons = n*(n-1) ~ n2
 

Best Case Complexity: O(n)
 When the array is already sorted, the outer loop runs for n number of times whereas the inner loop doesn't run in the least. So, there is only n number of comparisons. Thus, complexity is linear.


 Average Case Complexity: O(n2)
 It occurs when the weather of an array is in jumbled order (neither ascending nor descending).

Space Complexity for Insertion sort algorithm


Space complexity is O(1) because of an additional variable key's used.


Insertion Sort Applications


The insertion sort is employed when:
  •  the array features a small number of elements
  •  there are only a couple of elements left to be sorted

insertion sort algorithm with example in c

// Insertion sort in C

#include <stdio.h>

// Function to print an array
void printArray(int array[], int size) {
 for (int i = 0; i < size; i++) {
 printf("%d ", array[i]);
 }
 printf("\n");
}

void insertionSort(int array[], int size) {
 for (int step = 1; step < size; step++) {
 int key = array[step];
 int j = step - 1;

 // Compare key with each element on the left of it until a component smaller than
 // it's found.
 // For descending order, change keyarray[j].
 while (key < array[j] && j >= 0) {
 array[j + 1] = array[j];
 --j;
 }
 array[j + 1] = key;
 }
}

// Driver code
int main() {
 int data[] = {9, 5, 1, 4, 3};
 int size = sizeof(data) / sizeof(data[0]);
 insertionSort(data, size);
 printf("Sorted array in ascending order:\n");
 printArray(data, size);
}

 

Thursday, July 9, 2020

Bubble Sort algorithm in C and bubble sort program in c

July 09, 2020 0
Bubble Sort algorithm in C and bubble sort program in c

What is Sorting(Bubble Sort in C) - Definition


Often in the real world, we are alleged to arrange data during a particular order. as an example, during our college days, we are told to face within the queue supported our heights. Another example is that the attendance register at school/college which contains our names arranged in alphabetical order.


Bubble Sort algorithm in C and bubble sort program in c
Bubble Sort algorithm in C and bubble sort program in c

These data arrangements give easier access to data for future use forex. finding "Drake" in an attendance register of 100 students. The arrangement of knowledge during a particular order is named as sorting of the info by that order. 2 of the foremost commonly used orders are:

 Ascending order for Bubble Sort in C algorithm:


 while sorting the info in ascending order, we attempt to arrange the info during a way such each element is in how “smaller than” its successor. This “smaller one” relation is an ordered relation over the set from which the info is taken. As an easy example, the numbers 1, 2, 3, 4, 5 are sorted in ascending order. Here, the “smaller than” relation looks like < operator. and seen as, 1 < 2 < 3 < 4 < 5

Check also :- Data structure in Hindi 


Descending order Bubble Sort algorithm in C:


 descending order is the exact opposite of ascending order. Given a knowledge that's sorted in ascending order, reverse it and you'll get the info in descending order.

Due to the similar nature of the two orders, we frequently drop the particular order and that we say - we would like to sort the info. This generally means we would like the info to be sorted in ascending order. Before we get into the small print of the algorithm, allow us to understand the matter statement.

Problem statement for bubble sort in c


We are given an array (or a list) of knowledge. We also are given how to “order” the weather present within the data. Now, we are asked to arrange the info as per the given order. As an example, we are given an array of integers: [5, 1, 4, 2, 3]. We are given the “order” as “smaller than”. 


So, we are asked to rearrange the weather of this array in such how that every element is smaller than its successor. Basically, we'd like to seek out how to sort this array in order that the ultimate array obtained is [1, 2, 3, 4, 5]. 

There are several techniques/algorithms to realize this ordered output array. One such well-known technique that we'll discuss during this blog is named Bubble Sort.


Bubble Sort Algorithm in C - Introduction


Bubble Sort in C may be an algorithm where we repeatedly iterate through the array and swap adjacent elements that are unordered. We repeat these steps until the array is sorted.

As an example, for the array mentioned above - [5, 1, 4, 2, 3] we will see that 5 shouldn't get on the left of 1 then, we swap them to get: [1, 5, 4, 2, 3]. Next, we see that 5 should again not get on the left of 4. We swap 5 and 4 to urge [1, 4, 5, 2, 3]. We repeat this for five and a couple of and subsequently for five and three to urge [1, 4, 2, 3, 5].

As are often seen - after one “pass” over the array, the most important element (5 during this case) has reached its correct position - extreme right. allow us to attempt to repeat this process.

(1, 4) is correct. However, (4, 2) is an incorrect order. Therefore, we swap 4 and a couple of to urge [1, 2, 4, 3, 5]. Now again, (4, 3) is wrong so we do another swap and obtain [1, 2, 3, 4, 5].

As are often seen, the array is sorted!

this is the way how's bubble sort in C programming works.

#include  <stdio.h>
  
void swap(int *tp, int *qp) 
{ 
    int temp = *tp; 
    *tp = *qp; 
    *qp = temp; 
} 
  //function for bubble sort algorithm
void bubbleSort(int arr[], int n) 
{ 
   int k, l; 
   for (k = 0; k < n-1; k++)       
     
       for (l = 0; l < n-k-1; l++)  
           if (arr[l] > arr[l+1]) 
              swap(&arr[j], &arr[l+1]); 
} 
  

void printArray(int arr[], int size) 
{ 
    int k; 
    for (k=0; k < size; k++) 
        printf("%d ", arr[k]); 
    printf("\n"); 
} 
  
int main() 
{ 
    int arr[] = {1, 2, 4, 3, 5}; 
    int n = sizeof(arr)/sizeof(arr[0]); 
    bubbleSort(arr, n); 
    printf("Sorted array: \n"); 
    printArray(arr, n); 
    return 0; 
} 

Bubble Sort in C - Explanation


In the first “pass” through the array, the most important element will always get swapped until it's placed to the acute right. this is often because this largest element will always break the specified order. So, at the top of the primary pass, the most important element will always reach its correct position.

Now that the most important element has reached its correct position (for instance, 5 reached the last position), we will simply ignore it and consider the remainder of the array ([1, 4, 2, 3] within the above case).


 Here, the most important element within the remainder of the array (which is 4) is going to be nothing but the second largest element within the array. By the above recursive argument, this second largest array will then reach the last position within the remaining array ([1, 2, 3, 4]). this is often nothing but a recursive argument on the remaining array.

This continues until for n iterations where n = number of elements within the array. Finally, the array gets sorted.

Bubble sorting program in C


We loop n times - once for every element of the array. once I = 0, with the j loop, the most important element of the array reaches its correct position. once I = 1, with the j loop, the second largest element of the array reaches its correct position. So on then forth.


Conclusion for Bubble sort in c


Bubble sort in c may be a fairly simple algorithm. It forms a stimulating example of how simple computations are often wont to perform more complex tasks. However, there's one issue with the algorithm - it's relatively slower compared to other sorting algorithms. to know that, allow us to take a glance at the loops involved - there are 2 loops:

 First, the outer loop of variable i that goes from i = 0 to i = n - 1.
 for every iteration of the outer i loop, the inner loop of variable j goes from j = 0 to j = n - i - 2.

We can consolidate the amount of iterations to ascertain that:

 once I = 0, the inner j loop goes from j = 0 to j = n - 2
 once I = 1, the inner j loop goes from j = 0 to j = n - 3
 once I = 2, the inner j loop goes from j = 0 to j = n - 4
 once I = n - 2, the inner j loop goes from j = 0 to j = 0

We can sum this up to ascertain that the entire iterations are (n - 2) + (n - 3) + (n - 4) … + 1 + 0 = (n - 2) * (n - 3) / 2 = (n2 - 5n + 6) / 2 = n2/2 - 2.5n + 3As are often seen, this term is proportional to n2 (the largest power of n is n2).


 Mathematically, this is often stated as - bubble sort algorithm is of O(n2) complexity. This isn’t the simplest because when n is large (say n = 106), n2 is large (n2 = 1012). Therefore, it'll take tons of iterations for the algorithm to finish. 

this is often undesirable. There are some better algorithms like merge sort in C, etc that take O(nlog2n) iterations. logn is far smaller than n. As an example, when n = 230 (which is approximately 109), log2n is simply 30). 

Nevertheless, bubble sort is a stimulating algorithm and maybe a good way for beginners to know how sorting works.