Advertisement
thinhckhcmus

Các Sort Cơ Bản ( C++ )

Sep 25th, 2019
151
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.03 KB | None | 0 0
  1. <<<<<<<<<<<<<<<<<<<sort.h>>>>>>>>>>>>>>>>>>>>>>
  2. #pragma once
  3. #include <iostream>
  4. #include <fstream>
  5. using namespace std;
  6. void nhapmang(int[], int);
  7. void xuatmang(int[], int);
  8. void xuatmang2(int[], int );
  9. void selection_sort(int[], int);
  10. void insertion_sort(int[], int);
  11. void interchange_sort(int [], int);
  12. <<<<<<<<<<<<<<<<<<<<sort.cpp>>>>>>>>>>>>>>>>>>>
  13. #include "sort.h"
  14. #include <fstream>
  15. using namespace std;
  16. #define MAX 100
  17. int main()
  18. {
  19. ifstream file;
  20. file.open("filetext.txt");
  21. int x[100];
  22. int n = 0;
  23. int j = 0;
  24. while (!file.eof())
  25. {
  26. n++;
  27. file >> x[j];
  28. j++;
  29. }
  30. file.close();
  31. xuatmang(x, n);
  32. selection_sort(x, n);
  33. cout << "sap xep chon la: ";
  34. xuatmang2(x, n);
  35. insertion_sort(x, n);
  36. cout << "sap xep chen la: ";
  37. xuatmang2(x, n);
  38. interchange_sort(x, n);
  39. cout << "sap xep doi truc tiep la: ";
  40. xuatmang2(x, n);
  41. system("pause");
  42.  
  43. }
  44. void nhapmang(int a[], int n)
  45. {
  46. do
  47. {
  48. cout << "nhap so luong mang: ";
  49. cin >> n;
  50. if (n<1 || n>MAX)
  51. {
  52. cout << "nhap so luong sai , xin moi nhap lai";
  53. }
  54. } while (n<1 || n>MAX);
  55.  
  56. for (int i = 0; i < n; i++)
  57. {
  58. cout << "nhap A[" << i << "]:";
  59. cin >> a[i];
  60. }
  61. }
  62. void xuatmang(int a[], int n)
  63. {
  64. for (int i = 0; i < n-1; i++)
  65. {
  66. cout << " " << a[i];
  67. }
  68. cout << "\n";
  69. }
  70. void xuatmang2(int a[], int n)
  71. {
  72. for (int i = 1; i < n; i++)
  73. {
  74. cout << " " << a[i];
  75. }
  76. cout << "\n";
  77. }
  78. void selection_sort(int a[], int n)//sap xep lua chon
  79. {
  80. for (int i = 0; i <n-1; i++)
  81. {
  82. int min = i;
  83. for (int j = i+1; j < n; j++)
  84. {
  85. if (a[j]<a[min])
  86. {
  87. min = j;
  88. }
  89. swap(a[min], a[i]);
  90.  
  91. }
  92. }
  93. }
  94. void insertion_sort(int a[], int n)// sap xep chen
  95. {
  96. for (int i = 1; i < n; i++)
  97. {
  98. int x = a[i];
  99. int j = i;
  100. while (j > 0 && a[j - 1] > x)
  101. {
  102. a[j] = a[j - i];
  103. j--;
  104. }
  105. a[j] = x;
  106. }
  107. }
  108. void interchange_sort(int a[], int n)// sap xep doi truc tiep
  109. {
  110. for (int i = 0; i < n-1; i++)
  111. {
  112. for (int j = i + 1; j < n; j++)
  113. {
  114. if (a[i] > a[j])
  115. {
  116. swap(a[i], a[j]);
  117. }
  118. }
  119. }
  120. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement