</pre><pre name="code" class="cpp">#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
void QuickSort(int *gDigits, int nLen);
int main(int argc, char **argv){
//if there is no digits input as arguments,
if (1 == argc){
printf("Please input the digits!\n");
return EXIT_FAILURE;
}
//convert the string to int number
int *gDigits;
//alloc the memory for the grid
gDigits = (int *)malloc((argc - 1)*sizeof(int));
for (int i = 1; i < argc; i++)
gDigits[i - 1] = atoi(argv[i]);
QuickSort(gDigits, argc - 1);
for (int i = 0; i < argc - 1; i++)
printf("%d ", gDigits[i]);
free(gDigits);
gDigits = NULL;
}
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+ Function Name: QuickSort +
+ Descriptions : Use the theory of quick sort to sort the grid. +
+ Input Values: gDigits -- Store the digits waitting to be sorted.+
+ nLen -- The length of the grid. +
+ Output Values: Nil +
+ Return Values: Nil +
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
void QuickSort(int *gDigits, int nLen){
int nForwardIndex = 0;
int nRearIndex = nLen - 1;
//There is no need to sort, if the length is 1.
if (nLen <= 1)
return;
//Assign the key value which is compared with other digits as the referential value.
int nKey = gDigits[0];
bool bIsForward = false;
//The process continues until the two index equals
while (nForwardIndex < nRearIndex){
//Traverse backward to find the digit which is smaller than nKey.
if (gDigits[nRearIndex] < nKey){
//Swap the value.
gDigits[nForwardIndex] = gDigits[nRearIndex];
gDigits[nRearIndex] = nKey;
bIsForward = true;
}
//Traverse forward to find the digit which is larger than nKey.
else if (gDigits[nForwardIndex] > nKey){
//Swap the value.
gDigits[nRearIndex] = gDigits[nForwardIndex];
gDigits[nForwardIndex] = nKey;
bIsForward = false;
}
//Deal with the index.
bIsForward ? nForwardIndex++ : nRearIndex--;
}
//The digits are separated into two parts and sort these two parts with quick sort.
QuickSort(gDigits, nForwardIndex + 1);
QuickSort(gDigits + nForwardIndex + 1, nLen - nForwardIndex - 1);
}
QuickSort(快速排列)
最新推荐文章于 2022-03-17 09:10:00 发布