fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. int arr[20];
  5. int n;
  6.  
  7. void input() {
  8.  
  9. while(true)
  10. {
  11.  
  12. cout << "Input Maximum Length = ";
  13. cin >> n;
  14.  
  15. if (n <= 20) {
  16. break;
  17. } else {
  18. cout << "n is bigger than 20";
  19. }
  20.  
  21. }
  22.  
  23. cout << endl;
  24. cout << "=======================" << endl;
  25. cout << "Enter Elements of Array" << endl;
  26. cout << "=======================" << endl;
  27.  
  28. for(int i = 0; i < n; i++) {
  29. cout << "Data - " << i+1 << " : ";
  30. cin >> arr[i];
  31. cout << endl;
  32. }
  33.  
  34. }
  35.  
  36. void display() {
  37. cout << endl;
  38. cout << "============" << endl;
  39. cout << "Sorted Array" << endl;
  40. cout << "============" << endl;
  41.  
  42. for(int i =0; i < n; i++) {
  43. cout << "Data " << i+1 << " : " << arr[i] << endl;
  44. }
  45. }
  46.  
  47.  
  48. void bubbleSortAlgorithm() {
  49. // set pass = 1
  50. int pass = 1;
  51. //pass <= n-1, go to step 2
  52. do {
  53. // reapeat step 3 selama J from 0 to n-1 pass
  54. for ( int j = 0 ; j <= n-1 -pass; pass < j++)
  55. {
  56. //if the element at index j is greater than the
  57. //j + 1, swap the two elements
  58. if(arr[j] > arr[j + 1]) {
  59. int tmp;
  60. tmp = arr[j];
  61. arr[j] = arr[j + 1];
  62. arr[j + 1] = tmp;
  63. }
  64. }
  65. //increment pass by 1
  66. pass = pass + 1;
  67. } while (pass <= n-1); //atau pass < n
  68.  
  69. }
  70.  
  71. int main() {
  72.  
  73. input();
  74. bubbleSortAlgorithm();
  75. display();
  76.  
  77. }
Success #stdin #stdout 0.01s 5276KB
stdin
5
4 2 7 9 2
stdout
Input Maximum Length = 
=======================
Enter Elements of Array
=======================
Data - 1 : 
Data - 2 : 
Data - 3 : 
Data - 4 : 
Data - 5 : 

============
Sorted Array
============
Data 1 : 2
Data 2 : 2
Data 3 : 4
Data 4 : 7
Data 5 : 9