简体   繁体   中英

Big O How to trace iteration in QuickSort Algorithm? C

I have the following C code Quick Sort algorithm.

#include <stdio.h>
#include <stdbool.h>

int list[] = {8, 1, 3, 4, 2, 10, 4, 6};
//int list[] = {2, 1, 10, 4, 5, 11, 12, 6};
//int list[] = {35, 33, 42, 10, 14, 19, 27, 44, 26, 31};
int main(int argc, char **argv)
{

    printf("Unsorted list is: ");
    printArray(list);
    quickSort(0, 7);
    printf("Sorted list is: ");
    printArray(list);

    return 0;
}

int partition(int left, int right, int pivot){

    int leftPointer = left -1;
    int rightPointer = right;
    while(true){

        while(list[++leftPointer] < pivot){
         //do nothing
//       printf("proses index kiri %d\n", leftPointer);

        }

        while(rightPointer > 0 && list[--rightPointer] > pivot){
         //do nothing
//       printf("proses index kanan %d\n", rightPointer);
        }

        if(leftPointer >= rightPointer){
            break;
        }else{
            printf("item swapped :%d,%d\n", 
            list[leftPointer],list[rightPointer]);

            swap(leftPointer, rightPointer);
//          return;
//          left++;
//          right--;
        }

    }
    printf("pivot swapped :%d,%d\n", list[leftPointer],list[right]);
    swap(leftPointer, right);
    printf("pivot index %d\n", leftPointer);
    return leftPointer;

}

void quickSort(int left, int right){
    if(right - left <= 0){
        return;
    }else{
        int pivot = list[right];
        int pIndex = partition(left, right, pivot);
        quickSort(left, pIndex-1);
        quickSort(pIndex+1, right);
//      printf("aman lanjut proses");
    }
}

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

void swap(int left, int right){
    //variabel sementara untuk menampung i
    int temporary = list[left];

    //tukar posisi, sehingga yg kecil di kiri, yg besar di kanan.
    list[left] = list[right];
    list[right] = temporary;
}

Where should I put "printf" to indicate step of iteration (trace)?

Because the goal is I want to check/count with the current data how the complexity in Big O notation? meet the best, average, or worst case.

Big O says that every "operation" has the same cost. Even it is is as trivial as incrementing a pointer. So you need to set up a global counter, then increment it with every inner loop. So the two while leftpointer and while rightpointer loops, plus the while true loop. One increment for each pass.\\

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM