快速排序-确定所需的比较和交换次数

时间:2018-10-31 20:52:42

标签: c++ quicksort

我正在尝试使用QuickSort排序此列表S = [17,-10、7、19、21、23,-13、31、59]。

当前,以下代码输出对整个列表进行排序所需的交换总数。

我将如何更改它以查找将S [1](17)移到正确位置需要多少交换和比较?

#include<stdio.h>
#include <iostream>
using namespace std; 

int swapc = 0;

void swap(int* a, int* b)
{
    int t = *a;
    *a = *b;
    *b = t;
    swapc++;
}

int partition(int arr[], int low, int high)
{
    int pivot = arr[high];  
    int i = (low - 1);  

    for (int j = low; j <= high - 1; j++)
    {
        if (arr[j] <= pivot)
        {
            i++;    
            swap(&arr[i], &arr[j]);
        }
    }
    swap(&arr[i + 1], &arr[high]);
    return (i + 1);
}

void quickSort(int arr[], int low, int high)
{
    if (low < high)
    {
        /* pi is partitioning index, arr[p] is now
           at right place */
        int pi = partition(arr, low, high);

        quickSort(arr, low, pi - 1);
        quickSort(arr, pi + 1, high);
    }
}

void printArray(int arr[], int size)
{
    int i;
    for (i = 0; i < size; i++)
        printf("%d ", arr[i]);
    printf("n");
}

// Driver program to test above functions
int main()
{
    int arr[] = { 17, -10, 7, 19, 21, 23, -13, 31, 59 };
    int n = sizeof(arr) / sizeof(arr[0]);
    quickSort(arr, 0, n - 1);
    printf("Sorted array: n");
    printArray(arr, n);
    cout << swapc;
    return 0;
}

0 个答案:

没有答案