Advertisement
Gesh4o

BubleSort

Oct 4th, 2015
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.15 KB | None | 0 0
  1. using System;
  2. using System.Linq;
  3.  
  4. class BubleSort
  5. {
  6. static void Main()
  7. {
  8. Random rnd = new Random();
  9. int[] array = new int[10];
  10. for (int i = 0; i < array.Length; i++)
  11. {
  12. array[i] = rnd.Next(101);
  13. }
  14. for (int i = 0; i < array.Length; i++)
  15. {
  16. Console.Write("{0,4}", array[i]);
  17. }
  18. Console.WriteLine();
  19.  
  20. bool swapped = false;
  21. int counter = array.Length;
  22. do
  23. {
  24. counter--;
  25.  
  26. int index = 0;
  27. int leftNumber = array[index];
  28. int rightNumber = array[index+1];
  29.  
  30. for (int i = 0; i < counter; i++)
  31. {
  32. if (leftNumber> rightNumber)
  33. {
  34. //Switching positions.
  35. int temp = array[index];
  36. array[index] = array[index + 1]; //goes off in next loop.
  37. array[index + 1] = temp; //turns to be leftNumber in next loop.
  38.  
  39. //Working with index's values.
  40. leftNumber = temp; //Getting the value of the higher number.
  41.  
  42. if (i== counter-1) //For last iteration of the loop, when if leftNumber > rightNumber only exchanges their position.
  43. {
  44. swapped = true;
  45. break;
  46. }
  47. rightNumber = array[index + 2];
  48. }
  49. else
  50. {
  51. if (i == counter - 1) //For last iteration of the loop, when if leftNumber < ends the for loop.
  52. {
  53. swapped = true;
  54. break;
  55. }
  56. leftNumber = array[index + 1];
  57. rightNumber = array[index + 2];
  58. }
  59. index++;
  60. }
  61. } while (swapped && counter>1);
  62. for (int i = 0; i < array.Length; i++)
  63. {
  64. Console.Write("{0,4}", array[i]);
  65. }
  66. Console.WriteLine();
  67. }
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement