Advertisement
HeatPulse

lab5-2 Shaker(cocktail)sortiranje

Nov 12th, 2019
2,446
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.96 KB | None | 0 0
  1. haker (cocktail) сортирање Problem 2 (0 / 0)
  2. Дадена е низа со N природни броеви. Треба да се сортира низата со помош на таканареченото shaker (cocktail) сортирање. Ова сортирање е варијација на сортирањето со меурчиња (bubble sort) со тоа што во секоја итерација низата се изминува два пати. Во првото поминување најмалиот елемент се поместува на почетокот на низата, а при второто најголемиот елемент се поместува на крајот. Во првиот ред од влезот даден е бројот на елементи во низата N, а во вториот ред се дадени броевите. На излез треба да се испечати низата по секое изминување во посебен ред.
  3.  
  4. Име на класата: ShakerSort
  5.  
  6.  
  7. import java.io.BufferedReader;
  8. import java.io.IOException;
  9. import java.io.InputStreamReader;
  10.  
  11. public class ShakerSort {
  12.  
  13. static void shakerSort(int a[], int n)
  14. {
  15. int minCounter = 0;
  16. int maxCounter = 0;
  17. boolean done = false;
  18. for (int j=0; j < (a.length+1)/2; ++j) {
  19.  
  20. done = true;
  21.  
  22. //bubbleSortMin
  23. for (int i = a.length-1; i > minCounter; --i) {
  24. if (a[i] < a[i-1]) {
  25. int temp = a[i];
  26. a[i] = a[i-1];
  27. a[i-1] = temp;
  28. done = false;
  29. }
  30. }
  31. ++minCounter;
  32. write(a);
  33.  
  34. //bubbleSortMax
  35. for (int i= maxCounter; i < a.length -1; ++i ) {
  36. if (a[i] > a[i+1]) {
  37. int temp = a[i];
  38. a[i] = a[i+1];
  39. a[i+1] = temp;
  40. done = false;
  41. }
  42. }
  43. ++maxCounter;
  44. write(a);
  45. if (done)
  46. break;
  47. }
  48. }
  49.  
  50. static void write(int [] a) {
  51. int i;
  52. for (i=0; i<a.length; ++i)
  53. System.out.print(a[i] + " ");
  54. System.out.println();
  55. }
  56.  
  57.  
  58. public static void main(String[] args) throws IOException{
  59. int i;
  60. BufferedReader stdin = new BufferedReader( new InputStreamReader(System.in));
  61. String s = stdin.readLine();
  62. int n = Integer.parseInt(s);
  63.  
  64. s = stdin.readLine();
  65. String [] pom = s.split(" ");
  66. int [] a = new int[n];
  67. for(i=0;i<n;i++)
  68. a[i]=Integer.parseInt(pom[i]);
  69. shakerSort(a,n);
  70. }
  71. }
  72.  
  73. Sample input
  74. 8
  75. 6 10 13 5 8 17 2 5
  76. Sample output
  77. 2 6 10 13 5 8 17 5
  78. 2 6 10 5 8 13 5 17
  79. 2 5 6 10 5 8 13 17
  80. 2 5 6 5 8 10 13 17
  81. 2 5 5 6 8 10 13 17
  82. 2 5 5 6 8 10 13 17
  83. 2 5 5 6 8 10 13 17
  84. 2 5 5 6 8 10 13 17
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement