Quick Sort - Detailed Version

 avatar
itsLu
c_cpp
2 months ago
1.7 kB
2
Indexable
Never
#include <iostream>
using namespace std;

/*لازم نخلي الكاونترز جلوبال عشان ده ريكرجن لو عرفتهم جوا الفانكشن
  مش هيشتغلوا لأن كل ندهة عالفانكشن هترجع الكاونترز اصفار وده مش عايزينه*/
int cCounter = 0, swapCounter = 0;

void quick_sort (int arr[], int l, int r)
{
    if (l < r)
        {
        int pivot = arr[l], leftcounter = l + 1, rightcounter = r, temp;
        while (leftcounter <= rightcounter)
        {
            while (arr[leftcounter] <= pivot && leftcounter <= r)
            {
                leftcounter++;
                cCounter++;
            }
            while (arr[rightcounter] >= pivot && rightcounter > l)
            {
                rightcounter--;
                cCounter++;
            }
            if (leftcounter < rightcounter)
            {
                temp = arr[rightcounter];
                arr[rightcounter] = arr[leftcounter];
                arr[leftcounter] = temp;
                swapCounter++;
            }
        }
        temp = arr[l];
        arr[l] = arr[rightcounter];
        arr[rightcounter] = temp;
        swapCounter++;
        quick_sort(arr, l, rightcounter - 1);
        quick_sort(arr, rightcounter + 1, r);
        }
}

int main()
{
    int arr[5] = {5, 4, 3, 2 , 1};
    Quick_Sort(arr, 0, 4);
    cout << endl << "Number of Comparisons: " << cCounter << "\tNumber of Swaps: " << swapCounter << endl;
//اللوب الجاية دي عشان تطبع الأراي بعد الترتيب ممكن تكرفله عادي
    for (int k = 0 ; k < 5 ; k++)
        cout << arr[k] << "\t";
}
Leave a Comment