Thuật toán sắp xếp nhanh Quick Sort
- Mã: Chọn tất cả
#include <iostream>
using namespace std;
void quickSort(int Data[], int l , int r)
{
// If the first index less or equal than the last index
if (l <= r)
{
// Create a Key/Pivot Element
int key = Data[(l+r)/2];
// Create temp Variables to loop through array
int i = l;
int j = r;
while (i <= j)
{
while (Data[i] < key)
i++;
while (Data[j] > key)
j--;
if (i <= j)
{
swap(Data[i], Data[j]);
i++;
j--;
}
}
// Recursion to the smaller partition in the array after sorted above
if (l < j)
quickSort(Data, l, j);
if (r > i)
quickSort(Data, i, r);
}
}
int main()
{
int arr[] {32,71,12,45,26,80,53,33,-7,99,1,5,2,-3,-100};
int n = sizeof(arr) / sizeof(arr[0]); // so luong phan tu trong mang
quickSort(arr, 0, n-1);
cout << "So luong phan tu trong mang: " << n << endl;
for (int i : arr) {
cout << i << " ";
}
return 0;
}