samedi 20 février 2016

binary search and add a number in the right position in sorted array ,,, but no changes at the array

I made a program that allow the user to add a number and search for the right position with binary search in sorted array


and this is the code


#include <stdio.h>

int main(void)
{
    int array[100];
    int len=0;
    int help=0;
    int num=0;
    int middel=0;
    int first=0;
    int last=0;

    printf("enter the number of elements :");
    scanf("%d",&len);
    for(int i=0;i<len;i++)
    {
        printf("enter the (%d) element :",i+1);
        scanf("%d",&array[i]);
    }
    for(int i=len-1;i>0;i--)
    {
        for(int j=0;j<i;j++)
        {
            if(array[j]>array[j+1])
            {
                help=array[j];
                array[j]=array[j+1];
                array[j+1]=help;
            }
        }
    }
    printf("enter the number you want to add :");
    scanf("%d",&num);
    first=0;
    last=len-1;
    middel=(first+last)/2;
    while(first<last)
    {
        if(num<array[middel])
        {
            last=middel-1;
            middel=(first+last)/2;
        }
        else if(num>array[middel])
        {
            first=middel+1;
            middel=(first+last)/2;
        }
        else if (first==last)
        {
            if(array[first]>num)
            {
                len++;
                for(int i=len-1;i>first;i--)
                {
                    array[i+1]=array[i];
                }
                array[first]=num;
            }
            else if(array[first]<=num)
            {
                len++;
                for(int i=len-1;i>first+1;i--)
                {
                    array[i+1]=array[i];
                }
                array[first+1]=num;
            }
        }
    }
    for(int i=0;i<len;i++)
    {
        printf("%d,",array[i]);
    }
    printf("\n");
    return 0;
}


note :: there are no compiler errors


I tried to wright my own way with codes so try to help me not change my way


thanks any way

Aucun commentaire:

Enregistrer un commentaire