Monday, November 25, 2013

Circular right shift of an array.

Problem:
Write a program to do circular right shift of an array.

e.g. Original array: 1 2 3 4 5 6 7
Circular right shift by 3 gives: 5 6 7 1 2 3 4

Algorithm:
  • If the value of the Shift is greater than the Size of the Array, overwrite the shift value by the Remainder of Shift divided by Size of the array.
  • Take a local array with size equal to the Shift value.
  • Store the part of array to be shifted in local array.
  • Shift the original array to the right by the value equal to Shift.
  • Copy the local array in the front of the original array starting at index zero.

#include "stdio.h"

#define SIZE 9

void circularRightShift(int *arr, int size, int shift)
{
 if ((shift == size) || (shift == 0))
     printf("No need to shift: Shift value and Size of array is same. \n");
 if (shift > size)
     shift = shift%size;

 int localarr[shift];

 for (int i = (size-shift); i < size; i++)
 {
     localarr[i - (size-shift)] = arr[i];
 }
 
 for (int j = (size-shift-1); j >= 0; j--)
 {
     arr[j+shift] = arr[j];
 }
 
 for(int k = 0; k < shift; k++)
 {
     arr[k] = localarr[k];
 }
}
int main(void)
{
    int arr[SIZE] = {1,2,3,4,5,6,7,8,9};
 
    circularRightShift(arr, SIZE, 20);

    for (int i = 0; i    {
       printf("  %d",arr[i]);
    }
    printf("\n");
    return 0;
}

Saturday, November 23, 2013

Write a program to find the first maximum and second maximum in an unsorted Array.

Easiest way to do this is to sort the array and then find the answer. In this case, time complexity will be equal to the sorting algorithm used i.e. minimum of O(nlogn), which is not the preferred way to do.
The better algorithm here is: take the first element of the array as the first maximum and second
element of the array as second maximum. Then loop through all elements:
  • If the number is larger than max then make it max, and make old max to second max.
  • Else if it is more than second max and not equal to first max then make it the second max.
  • In all other cases drop that number.
Code for your reference:

#include "stdio.h"

#define SIZE 10

void getFirstSecondMax(int *arr, int size)
{
    int i, max, sec_max;
    max  = arr[0];
    sec_max = arr[1];
    
    if (size < 2)
    {
        printf("Size of the Array is smaller than 2.\n");
        return;
    }
    for(i = 0; i < size; i++)
    {
        if(arr[i] > max) 
 {
            sec_max = max;
            max = arr[i];
        }
        else if((arr[i] > sec_max) && (arr[i] != max))
            sec_max = arr[i];
    }
    printf("First Maximum = %d, Second Maximum = %d\n", max, sec_max);
}

int main(void)
{
    int arr[SIZE] = {8, 4, 17, 1, 2, 1, 3, 18, 21, 4};    
    getFirstSecondMax(arr, SIZE);
}