【发布时间】:2017-08-13 20:22:26
【问题描述】:
代码确实运行。这是我正在研究的快速排序的一个有点不同的版本。我遇到了一些重大问题。首先,它将数组中的第一个元素打印为 n:例如(如果您设置 n = 3,即使您将数组中的第一个元素设为 1,它仍然会打印出 3 作为第一个元素)。此外,当您打印出排序后的版本时,它实际上并没有改变任何东西。
n = 3 的示例输入,
设置值 = 8 , 7 , 6
初始输出将等于 3 , 7 , 6
最终输出将等于 3 , 7 , 6
(输出应该是 6 , 7 , 8)
我在网上找不到任何与我的代码相似的代码,所以这可能是新的东西!谢谢。
//preprocessor directives and header files
#include <stdio.h>
#define MAX_ARRAY_SIZE 50
//function prototypes separated by data types
void print_array( int array[], int n ); // Print out the array values
void swap( int array[], int index1, int index2 ); // Swap two array elements.
void quicksort( int array[], int low, int high ); // Sorting algorithm
int populate_array( int array[] ); // Fill array with values from user.
int partition( int array[], int low, int high ); // Find the partition point (pivot)
//the main function
int main(void)
{
int array[MAX_ARRAY_SIZE];
//set n = to size of user created size of array
int n = populate_array(&array[MAX_ARRAY_SIZE]);
//print the original array to the screen
print_array(&array[MAX_ARRAY_SIZE], n );
//perform the algorithm
quicksort(array, 0, n-1);
printf("The array is now sorted:\n");
print_array(&array[MAX_ARRAY_SIZE], n);
return 0;
}
// *array and array[] are the same...
int populate_array(int array[])
{
int n = -1;
printf("Enter the value of n > ");
scanf("%d", &n);
if(n > MAX_ARRAY_SIZE)
{
printf("%d exceeds the maximum array size. Please try again.\n\n", n);
populate_array( &array[MAX_ARRAY_SIZE]);
}
else if(n < 0)
{
printf("%d is less than zero. Please try again.\n\n", n);
populate_array( &array[MAX_ARRAY_SIZE]);
}
else if(n == 0)
{
printf("%d Array of size 0? Please don't try this, and... Please try again.\n\n", n);
populate_array( &array[MAX_ARRAY_SIZE]);
}
else
{
for(int i = 0; i < n; i++)
scanf("%d", &array[i]);
}
printf("The initial array contains: \n");
return n;
}
void print_array(int array[], int n)
{
for(int i = 0; i < n; i++)
printf("%+5d\n", array[i]);
}
void quicksort(int array[], int low, int high)
{
if (low < high)
{
/* pivot is partitioning index, array[p] is now
at right place */
int pivot = partition(array, low, high);
// Separately sort elements before
// partition and after partition
quicksort(array, low, pivot - 1);
quicksort(array, pivot + 1, high);
}
}
int partition(int array[], int low, int high)
{
int pivot = array[high];
int i = low;
for (int j = low; j <= high- 1; j++)
{
// If current element is smaller than or
// equal to pivot
if (array[j] <= pivot)
{
swap(array, i, j);
i = i +1;
}
}
swap(array, i, high);
return i;
}
void swap(int array[], int index1, int index2)
{
int temp = array[index1];
array[index1] = array[index2];
array[index2] = temp;
}
【问题讨论】:
-
你对
&array[MAX_ARRAY_SIZE]有什么期望? -
&array[MAX_ARRAY_SIZE]: 最后一个元素的地址。 -
1) 这是 C 还是 C++? 2) 代码确实有效。 然后是 我遇到了一些重大问题。 看起来很奇怪。代码是否有效? 3) 当您将
&array[MAX_ARRAY_SIZE]传递给您的函数时——它们正在读取为数组分配的空间——调用未定义的行为。 -
为了更清楚,所有
foo(&array[MAX_ARRAY_SIZE], n);都应该是foo(array, n);。