A Simple Merge Sort Implementation [C#]

Merge Sort
MergeSort is a “divide and conquer” algorithm that splits an array into two halves (sub arrays) and recursively sorts each sub array before merging them back into one giant, sorted array.
In this blog, I will provide a simple implementation of MergeSort with comments on every significant line of code for beginners to quickly grasp the algorithm.
Pseudocode

mergeSort(array)

if array.length <= 1 then
return array 
left = new array
right = new array 
mid = left+ right/2
mergeSort(left)
mergeSort(right)
merge(left, right) 
  1. class MergeSort
  2.     {
  3.         public static int[] mergeSort(int[] array)
  4.         {
  5.             int[] left;
  6.             int[] right;
  7.             int[] result = new int[array.Length];
  8.             //As this is a recursive algorithm, we need to have a base case to 
  9.             //avoid an infinite recursion and therfore a stackoverflow
  10.             if (array.Length <= 1)
  11.                 return array;
  12.             // The exact midpoint of our array
  13.             int midPoint = array.Length / 2;
  14.             //Will represent our ‘left’ array
  15.             left = new int[midPoint];
  16.             //if array has an even number of elements, the left and right array will have the same number of 
  17.             //elements
  18.             if (array.Length % 2 == 0)
  19.                 right = new int[midPoint];
  20.             //if array has an odd number of elements, the right array will have one more element than left
  21.             else
  22.                 right = new int[midPoint + 1];
  23.             //populate left array
  24.             for (int i = 0; i < midPoint; i++)
  25.                 left[i] = array[i];
  26.             //populate right array        
  27.             int x = 0;
  28.             //We start our index from the midpoint, as we have already populated the left array from 0 to 
  29.             midpont
  30.             for (int i = midPoint; i < array.Length; i++)
  31.             {
  32.                 right[x] = array[i];
  33.                 x++;
  34.             }
  35.             //Recursively sort the left array
  36.             left = mergeSort(left);
  37.             //Recursively sort the right array
  38.             right = mergeSort(right);
  39.             //Merge our two sorted arrays
  40.             result = merge(left, right);
  41.             return result;
  42.         }
  43.         //This method will be responsible for combining our two sorted arrays into one giant array
  44.         public static int[] merge(int[] left, int[] right)
  45.         {
  46.             int resultLength = right.Length + left.Length;
  47.             int[] result = new int[resultLength];
  48.             //
  49.             int indexLeft = 0, indexRight = 0, indexResult = 0;
  50.             //while either array still has an element
  51.             while (indexLeft < left.Length || indexRight < right.Length)
  52.             {
  53.                 //if both arrays have elements
  54.                 if (indexLeft < left.Length && indexRight < right.Length)
  55.                 {
  56.                     //If item on left array is less than item on right array, add that item to the result array
  57.                     if (left[indexLeft] <= right[indexRight])
  58.                     {
  59.                         result[indexResult] = left[indexLeft];
  60.                         indexLeft++;
  61.                         indexResult++;
  62.                     }
  63.                     // else the item in the right array wll be added to the results array
  64.                     else
  65.                     {
  66.                         result[indexResult] = right[indexRight];
  67.                         indexRight++;
  68.                         indexResult++;
  69.                     }
  70.                 }
  71.                 //if only the left array still has elements, add all its items to the results array
  72.                 else if (indexLeft < left.Length)
  73.                 {
  74.                     result[indexResult] = left[indexLeft];
  75.                     indexLeft++;
  76.                     indexResult++;
  77.                 }
  78.                 //if only the right array still has elements, add all its items to the results array
  79.                 else if (indexRight < right.Length)
  80.                 {
  81.                     result[indexResult] = right[indexRight];
  82.                     indexRight++;
  83.                     indexResult++;
  84.                 }
  85.             }
  86.             return result;
  87.         }
  88.     }
You can now go ahead and call your MergeSort(array) method from Main to see the results.

Sending, Receiving And Deleting Emails In C#

Sending, Receiving And Deleting Emails In C#

Email, abbreviated for electronic mail, is a method of exchanging messages between people using electronics. It’s now being widely used in our daily communication. In this blog, I will show how to send, receive and delete email messages programmatically using C# and a .net Email component.

Prerequisite

Before start, we need to add reference to the project by use the following PowerShell command in Visual Studio Nuget Package Manager Console.

  1. PM> Install-Package Spire.Email

Using the code

Sending emails

MailMessage class is used to create email messages. To send email messages, we’ll need to use the SmtpClient class. For the following demo, I’m sending an email with plain text body, you can also create an email with html body by using the BodyHtml property of MailMessage object, instead of BodyText property.

  1. MailAddress addressFrom = “LeonDavisLD@outlook.com”;
  2. MailAddress addressTo = “Shawn_Smithhh@outlook.com”;
  3. MailMessage message = new MailMessage(addressFrom, addressTo);
  4. message.Subject = “Invitation”;
  5. message.BodyText = “Hi Shawn,\r\n” + “This Saturday is my birthday and my parents will hold a simple celebrating party for me. I am glad to invite you to come to the party. Blair, Emma and Roan will also be invited. I am sure we will have a good time. We will have dinner at 18:30 so that you are wished to come at 18:15. My mother is a good cook and you will enjoy the dishes. After the dinner, we will play some small games and then eat the cake. My parents and I sincerely expect you to come and hope to see you then.\r\n “ + “Sincerely Leon “;
  6. SmtpClient smtp = new SmtpClient();
  7. smtp.Host = “smtp.outlook.com”;
  8. smtp.ConnectionProtocols = ConnectionProtocols.Ssl;
  9. smtp.Username = addressFrom.Address;
  10. smtp.Password = “password”;
  11. smtp.Port = 587;
  12. smtp.SendOne(message);
  13. Console.WriteLine(“From : “ + message.From.ToString());
  14. Console.WriteLine(“To : “ + message.To.ToString());
  15. Console.WriteLine(“Subject: “ + message.Subject);
  16. Console.WriteLine(“——————- BODY —————–“);
  17. Console.WriteLine(message.BodyText);
  18. Console.WriteLine(“——————- END ——————“);
  19. Console.WriteLine(“Message Sent.”);
Sending, Receiving And Deleting Emails In C#
Sending, Receiving And Deleting Emails In C#

Receiving and saving emails

Pop3Client and ImapClient is used for receiving email messages. Let’s see how we can retrieve an email message from pop and imap server, and then save it to disk. When saving the email messages, we can choose the message format such as eml, emlx, mhtml and msg from the MailMessageFormat enumeration.

Using Pop3Client

  1. //Create a POP3 client
  2. Pop3Client pop = new Pop3Client();
  3. //Set host, username, password etc. for the client
  4. pop.Host = “outlook.office365.com”;
  5. pop.Username = “LeonDavisLD@outlook.com”;
  6. pop.Password = “password”;
  7. pop.Port = 995;
  8. pop.EnableSsl = true;
  9. //Connect the server
  10. pop.Connect();
  11. //Get the first message by its sequence number
  12. MailMessage message = pop.GetMessage(1);
  13. //Parse the message
  14. Console.WriteLine(“—————— HEADERS —————“);
  15. Console.WriteLine(“From : “ + message.From.ToString());
  16. Console.WriteLine(“To : “ + message.To.ToString());
  17. Console.WriteLine(“Date : “ + message.Date.ToString(CultureInfo.InvariantCulture));
  18. Console.WriteLine(“Subject: “ + message.Subject);
  19. Console.WriteLine(“——————- BODY —————–“);
  20. Console.WriteLine(message.BodyText);
  21. Console.WriteLine(“——————- END ——————“);
  22. //Save the message to disk using its subject as file name
  23. message.Save(message.Subject + “.eml”, MailMessageFormat.Eml);
  24. Console.WriteLine(“Message Saved.”);

Using ImapClient

  1. //Create an IMAP client
  2. ImapClient imap = new ImapClient();
  3. // Set host, username, password etc. for the client
  4. imap.Host = “outlook.office365.com”;
  5. imap.Port = 143;
  6. imap.Username = “LeonDavisLD@outlook.com”;
  7. imap.Password = “password”;
  8. imap.ConnectionProtocols = ConnectionProtocols.Ssl;
  9. //Connect the server
  10. imap.Connect();
  11. //Select Inbox folder
  12. imap.Select(“Inbox”);
  13. //Get the first message by its sequence number
  14. MailMessage message = imap.GetFullMessage(1);
  15. //Parse the message
  16. Console.WriteLine(“—————— HEADERS —————“);
  17. Console.WriteLine(“From : “ + message.From.ToString());
  18. Console.WriteLine(“To : “ + message.To.ToString());
  19. Console.WriteLine(“Date : “ + message.Date.ToString(CultureInfo.InvariantCulture));
  20. Console.WriteLine(“Subject: “ + message.Subject);
  21. Console.WriteLine(“——————- BODY —————–“);
  22. Console.WriteLine(message.BodyText);
  23. Console.WriteLine(“——————- END ——————“);
  24. //Save the message to disk using its subject as file name
  25. message.Save(message.Subject + “.eml”, MailMessageFormat.Eml);
  26. Console.WriteLine(“Message Saved.”);
Sending, Receiving And Deleting Emails In C#
Sending, Receiving And Deleting Emails In C#

Deleting emails

All email messages can be deleted using the DeleteAllMessages() method of Pop3Client class. We can also delete an specific email message with the DeleteMessage() method.

  1. //Create a POP3 client
  2. Pop3Client pop3 = new Pop3Client();
  3. //Set host, authentication, port and connection protocol
  4. pop3.Host = “outlook.office365.com”;
  5. pop3.Username = “LeonDavisLD@outlook.com”;
  6. pop3.Password = “password”;
  7. pop3.Port = 995;
  8. pop3.EnableSsl = true;
  9. //Connect the pop server
  10. pop3.Connect();
  11. //Get the number of messages before deleting message(s)
  12. Pop3MessageInfoCollection messages = pop3.GetAllMessages();
  13. Console.WriteLine(“Number of messages before deleting: “ + messages.Count);
  14. //Delete an email message by its sequence number
  15. pop3.DeleteMessage(2);
  16. //Delete all messages
  17. //pop3.DeleteAllMessages();
  18. //Get the number of messages after deleting message(s)
  19. messages = pop3.GetAllMessages();
  20. Console.WriteLine(“Number of messages after deleting: “ + messages.Count);
Sending, Receiving And Deleting Emails In C#
Sending, Receiving And Deleting Emails In C#

Conclusion

This blog only illustrates the send, receive and delete email functions using c#. The Spire.Email component has rich features such as search email messages, add and extract attachment, get the mailbox and message information, and manipulate folders etc. And it supports c#, vb.net, asp.net applications, you can try it yourself.