Advertisement
eddiehy

sorting demo

Nov 27th, 2015
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.39 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3. void bubble(int* data)
  4. {
  5. int i,j,temp;
  6. for (j=0;j<6;j++)
  7. {
  8. for (i=j+1;i<6;i++) //i<5才會執行, 所以不會爆
  9. {
  10. if (data[j]>data[i]) //遞增就是把最大值換到最後面
  11. {
  12. temp=data[i];
  13. data[i]=data[j];
  14. data[j]=temp;
  15. }
  16. }
  17. for (i=0;i<6;i++)
  18. {
  19. printf("%d ",data[i]);
  20. }
  21. printf("\n");
  22. }
  23. }
  24. void select(int* data)
  25. {
  26. int i,j,temp,min;
  27. for (j=0;j<6;j++) //最小值放最前面
  28. {
  29. min=j;
  30. for (i=j+1;i<6;i++) //i<5才會執行, 所以不會爆
  31. {
  32. if (data[min]>data[i]) //找出最小值
  33. {min=i;}
  34. }
  35. if (min!=j)
  36. {
  37. temp=data[j];
  38. data[j]=data[min];
  39. data[min]=temp;
  40. }
  41. for (i=0;i<6;i++)
  42. {
  43. printf("%d ",data[i]);
  44. }
  45. printf("\n");
  46. }
  47. }
  48. void insert(int* data)
  49. {
  50. int i,j,temp,max;
  51. for (i=0;i<6;i++) //遞增
  52. {
  53. max=i;
  54. for (j=i+1;j>=0;j--) //往後換的概念,泡泡跟選擇都往前換
  55. {
  56. if(data[j]>data[max])
  57. {
  58. temp=data[max];
  59. data[max]=data[j];
  60. data[j]=temp;
  61. max=j;
  62. }
  63. }
  64. for (j=0;j<6;j++)
  65. {
  66. printf("%d ",data[j]);
  67. }
  68. printf("\n");
  69. }
  70. }
  71.  
  72. int main()
  73. {
  74. int data[6];
  75. int i;
  76. int action;
  77. for (i=0;i<6;i++)
  78. {
  79. scanf("%d",&data[i]);
  80. }
  81. scanf("%d",&action);
  82. if (action==1)
  83. {bubble(data);}
  84. else if (action==2)
  85. {select(data);}
  86. else if (action==3)
  87. {insert(data);}
  88. return 0;
  89. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement