Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Sắp xếp tăng dần sử dụng Heap_Sort
- #include <stdio.h>
- void Out_Put(int n, int A[]);
- void In_Put(int n, int A[]);
- void Heap_Sort(int A[], int length,bool (*comparisonFunc)(int,int));
- void Build_Max_Heap(int A[], int length, bool(*comparisonFunc)(int,int));
- void swap(int& x, int& y);
- void Max_Heap(int A[], int i, int Heap_Size, bool (*comparisonFunc)(int, int));
- bool ascending(int left, int right);
- bool descending(int left, int right);
- int main()
- {
- int n;
- printf("Nhap so luong phan tu cua mang !\n");
- scanf_s("%d", &n);
- int* A = new int[n];
- In_Put(n, A);
- //Sắp xếp tăng dần
- printf("Sap xep tang dan : ");
- Heap_Sort(A, n,ascending);
- Out_Put(n, A);
- //Sắp xếp giảm dần
- printf("\nSap xep giam dan : ");
- Heap_Sort(A, n, descending);
- Out_Put(n, A);
- delete[] A;
- return 0;
- }
- void Heap_Sort(int A[], int length, bool (*comparisonFunc)(int, int))
- {
- int Heap_Size = length;
- Build_Max_Heap(A, length,comparisonFunc);
- for (int i = length - 1; i >= 1; i--)
- {
- swap(A[0], A[i]);
- Heap_Size = Heap_Size - 1;
- Max_Heap(A, 0, Heap_Size,comparisonFunc);
- }
- }
- void Build_Max_Heap(int A[], int length, bool (*comparisonFunc)(int,int))
- {
- int Heap_Size = length;
- for (int i = length / 2 - 1; i >= 0; i--)
- {
- Max_Heap(A, i, length,comparisonFunc);
- }
- }
- //Hàm đổi chỗ 2 số
- void swap(int &x, int &y)
- {
- int tmp = x;
- x = y;
- y = tmp;
- }
- //Sắp xếp tăng dần
- bool ascending (int left, int right)
- {
- return left > right;
- }
- //Sắp giảm dần
- bool descending(int left, int right)
- {
- return left < right;
- }
- void Max_Heap(int A[], int i, int Heap_Size, bool (*comparisonFunc)(int , int))
- {
- int l = 2 * i + 1;
- int r = 2 * i + 2;
- int largest;
- if ((l < Heap_Size) && comparisonFunc(A[l],A[i]))
- {
- largest = l;
- }
- else
- {
- largest = i;
- }
- if (r<Heap_Size && comparisonFunc(A[r],A[largest]))
- {
- largest = r;
- }
- if (largest != i)
- {
- swap(A[i],A[largest]);
- Max_Heap(A, largest, Heap_Size,comparisonFunc);
- }
- }
- //Xuất mảng
- void Out_Put(int n, int A[])
- {
- for (int i = 0; i < n; i++)
- {
- printf("%d ", A[i]);
- }
- }
- //Nhập mảng
- void In_Put(int n, int A[])
- {
- for (int i = 0; i < n; i++)
- {
- scanf_s("%d", &A[i]);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement