# Untitled

unknown
plain_text
a month ago
2.8 kB
2
Indexable
Never
```#include <iostream>
using namespace std;

void insertionSort(int arr[], int n) {
for (int i = 1; i < n; i++) {
int key = arr[i];
int j = i - 1;

while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
}

int main() {
int arr[] = {64, 25, 12, 22, 11};
int n = sizeof(arr) / sizeof(arr[0]);

cout << "Mang truoc khi sap xep: ";
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}

insertionSort(arr, n);

cout << "\nMang sau khi sap xep bang phuong phap chen truc tiep: ";
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
return 0;
}
Sắp xếp đổi chỗ trực tiếp:
CopyReplit#include <iostream>
using namespace std;

void bubbleSort(int arr[], int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
swap(arr[j], arr[j + 1]);
}
}
}
}

int main() {
int arr[] = {64, 25, 12, 22, 11};
int n = sizeof(arr) / sizeof(arr[0]);

cout << "Mang truoc khi sap xep: ";
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}

bubbleSort(arr, n);

cout << "\nMang sau khi sap xep bang phuong phap doi cho truc tiep: ";
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
return 0;
}
Sắp xếp nổi bọt:
CopyReplit#include <iostream>
using namespace std;

void push(int arr[], int n) {
for (int i = 0; i < n; i++) {
cout << "Nhap phan tu thu " << i << ": ";
cin >> arr[i];
}
}

void heapify(int arr[], int n, int i) {
int largest = i;
int left = 2 * i + 1;
int right = 2 * i + 2;

if (left < n && arr[left] > arr[largest]) {
largest = left;
}

if (right < n && arr[right] > arr[largest]) {
largest = right;
}

if (largest != i) {
swap(arr[i], arr[largest]);
heapify(arr, n, largest);
}
}

void heapSort(int arr[], int n) {
push(arr, n);

for (int i = n / 2 - 1; i >= 0; i--) {
heapify(arr, n, i);
}

for (int i = n - 1; i >= 0; i--) {
swap(arr[0], arr[i]);
heapify(arr, i, 0);
}
}

int main() {
int arr[] = {64, 25, 12, 22, 11};
int n = sizeof(arr) / sizeof(arr[0]);

cout << "Mang truoc khi sap xep: ";
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}

heapSort(arr, n);

cout << "\nMang sau khi sap xep bang phuong phap noi bot: ";
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
return 0;
}```