Friday, March 1, 2024

C# : Merge two sorted array

 int [] first=new int[]{1,3,5,9,11,15};

int [] second=new int[]{2,4,6,8};  

int n1=first.Length, n2=second.Length;
int [] third =new int[n1+n2];
Console.WriteLine($" n1={n1} and n2={n2}");
int i=0,j=0,k=0;

// Logic
// ==>i=0;j=0 =>1
// i=1,j=0 =>2
// i=1,j=1=>4
// i=1, j=2 => 5
// i=2, j=2 ==>6
// i=2, j=3 ==>8
// i=2,j=4 ==> exit lpoop ==>

while(i<n1 &&j<n2){  
    Console.WriteLine($" i={i} , j={j}, k={k}");
    if(first[i]>second[j]){
        third[k++]=second[j++];      
    }
    else{
        third[k++]=first[i++];        
    }    
}
while(i<n1){
    third[k++]=first[i++];
}
while(j<n2){
    third[k++]=second[j++];
}
foreach (var item in third)
{
    Console.WriteLine(item +"--");
}

No comments:

Post a Comment

C# Record type: Something to remember while using record types

  Record in c# provide a concise and expressive way to create immutable data types, record is a keyword in c#, we can use this keyword with ...