0% found this document useful (0 votes)
19 views

Btvntonghop

The document discusses four different sorting algorithms: selection sort, insertion sort, bubble sort, and merge sort. For each algorithm, it provides code examples in C++ to implement the sorting.

Uploaded by

Bùi Văn Nam
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Btvntonghop

The document discusses four different sorting algorithms: selection sort, insertion sort, bubble sort, and merge sort. For each algorithm, it provides code examples in C++ to implement the sorting.

Uploaded by

Bùi Văn Nam
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 5

Sắp xếp chọn

#include <bits/stdc++.h>

using namespace std;


int main()
{
int n;
cin >> n;
int a[n];
for (int i = 0; i < n; i++)
cin >> a[i];

for (int i = 0; i < n - 1; i++)


{
int k = i;
for (int j = i + 1; j < n; j++)
if (a[j] < a[k])
k = j;
swap(a[k], a[i]);

}
for (int j = 0; j < n; j++)
cout << a[j] << " ";
cout << endl;
}

Sắp xếp chèn


#include <bits/stdc++.h>
using namespace std;

int main() {
int n;
cin >> n;
int a[n];
for (int i = 0; i < n; i++)
cin >> a[i];

for (int i = 1; i < n; i++) {


int key = a[i];
int j = i - 1;
while (j >= 0 && a[j] > key) {
a[j + 1] = a[j];
j = j - 1;
}
a[j + 1] = key;
}
for (int i = 0; i < n; i++)
cout << a[i] << " ";
cout << endl;

return 0;
}

Sắp xếp nổi bọt

#include <bits/stdc++.h>
using namespace std;

int main() {
int n;
cin >> n;
int a[n];
for (int i = 0; i < n; i++)
cin >> a[i];

for (int i = 0; i < n - 1; i++) {


bool k = false;
for (int j = 0; j < n - i - 1; j++) {
if (a[j] > a[j + 1]) {
swap(a[j], a[j + 1]);
k = true;
}
}
if (k == false)
break;
}

for (int i = 0; i < n; i++)


cout << a[i] << " ";
cout << endl;

return 0;
}

Sắp xếp trộn

#include <bits/stdc++.h>
#define endl "\n"
using namespace std;
int main()
{
int n;
cin >> n;
vector<int> a(n);
for (int i = 0; i < n; i++)
cin >> a[i];
sort(a.begin(), a.end());
for (int i = 0; i < n; i++)
cout << a[i] << " ";
cout << endl;
}

You might also like