问题
I have to find time complexity of quick sort for BEST CASE INPUT in a c program & i have selected the last element of array as pivot. Now i know what input values i have to enter for best case, i.e., keep 1st middle element at the last place(pivot) & next pivot should be the next middle element. But i have to generate this kind of best case input array of very big sizes like 1000, 5000, 100000.., for quick sort. I can code, but can anyone please help me understand how to generate that kind of best case input array for quick sort with last pivot, using c programming. I just need the logic like how to generate that kind of array using c programming.
回答1:
Basically you need to do a divide & conquer approach akin to quicksort itself. Do it with a function that given a range of indices in the output:
generates the first-half partition by recursively calling itself
generates the second-half partition by recursively calling itself
inserts the pivot value after the second-half partition.
One thing to note is that since you are just generating output not sorting anything, you don't actually have to have any values as input -- you can just represent ranges logically as a start value at some index in the array and a count.
Some C# code is below; this is untested -- don't look if you want to do this yourself.
static int[] GenerateBestCaseQuickSort(int n)
{
var ary = new int[n];
GenerateBestCaseQuickSortAux(ary, 0, n, 1);
return ary;
}
static void GenerateBestCaseQuickSortAux(int[] ary, int start_index, int count, int start_value)
{
if (count == 0)
return;
if (count == 1)
{
ary[start_index] = start_value;
return;
}
int partition1_count = count / 2;
int partition2_count = count - partition1_count - 1; // need to save a spot for the pivot so -1...
int pivot_value_index = start_index + partition1_count;
int pivot_value = start_value + partition1_count;
GenerateBestCaseQuickSort(ary, start_index, partition1_count, start_value);
GenerateBestCaseQuickSort(ary, pivot_value_index, partition2_count, pivot_value+1);
ary[start_index + count - 1] = pivot_value;
}
来源:https://stackoverflow.com/questions/57693117/quick-sort-time-complexity-best-case-input