Advertisement
Guest User

Untitled

a guest
Jan 29th, 2020
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.29 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6.  
  7. namespace SortowaniePrzezScalanie
  8. {
  9. class Program
  10. {
  11. static void Scalanie(int[] tab, int lewy, int środek, int prawy)
  12. {
  13. //stores the starting position of both parts in temporary variables.
  14. int startLewej = lewy, startPrawej = środek + 1;
  15.  
  16. int[] tabPomocnicza = new int[prawy - lewy + 1];
  17. int k = 0;
  18.  
  19. for (int i = lewy; i <= prawy; i++)
  20. {
  21. if (startLewej > środek) //checks if first part comes to an end or not .
  22. tabPomocnicza[k++] = tab[startPrawej++];
  23.  
  24. else if (startPrawej > prawy) //checks if second part comes to an end or not
  25. tabPomocnicza[k++] = tab[startLewej++];
  26.  
  27. else if (tab[startLewej] < tab[startPrawej]) //checks which part has smaller element.
  28. tabPomocnicza[k++] = tab[startLewej++];
  29.  
  30. else
  31. tabPomocnicza[k++] = tab[startPrawej++];
  32. }
  33. for (startLewej = 0; startLewej < k; startLewej++)
  34. {
  35. /* Now the real array has elements in sorted manner including both
  36. parts.*/
  37. tab[lewy++] = tabPomocnicza[startLewej];
  38. }
  39. }
  40.  
  41. static void Sortowanie(int[] tab, int lewy, int prawy)
  42. {
  43. if (lewy < prawy)
  44. {
  45. int środek = (lewy + prawy) / 2; // defines the current array in 2 parts .
  46. Sortowanie(tab, lewy, środek); // sort the 1st part of array .
  47. Sortowanie(tab, środek + 1, prawy); // sort the 2nd part of array.
  48.  
  49. // merge the both parts by comparing elements of both the parts.
  50. Scalanie(tab, lewy, środek, prawy);
  51. }
  52. }
  53.  
  54. static void Main(string[] args)
  55. {
  56. int[] tab = { 23, 11, 45, 58, 17 };
  57. Sortowanie(tab, 0, tab.Length - 1);
  58. foreach (var item in tab)
  59. {
  60. Console.Write(item + " ");
  61. }
  62. Console.ReadKey();
  63. }
  64. }
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement