C kind of sorting



好的,这样一个函数可以将数组中的元素排列为所有元素小于给定值的元素被放置在较大元素左侧的位置大于给定值。

例如,如果数组内容为{4,6,2,9,1,73,10},并且x为5,则{4,3,2,1,9,7,6,10}是一个可能的解决方案,因为所有小于5的元素都在左边大于5的元素。

此外,使用括号[]是​被禁止的​除了在主函数中定义数组之外。

此外,实现一个打印数组内容的函数。两个函数都必须递归地实现。您只能访问数组的每个元素一次。

好的,所以这个"挑战",我不知道在给定的限制下是否可能。我试着用while循环来实现它,然后以某种方式将其转换为递归,但也不允许更改参数。有人知道解决办法吗。

我写了一些东西,但都是垃圾。

#include <stdio.h>
#define length 8
void selection(int array[],int size, int x){
int i=0;
int temp;
if(( array[i]>x ) && (array[i] > array[i+1])){
temp=array[i+1];
array[i+1]=array[i];
array[i]=temp;
i++;
selection(array+1,size-1,x)
}
else if(( array[i] > x) && ( array[i+1] > array[i])){
i++;
}
//This is not correct 
}
void printArray(int arr[], int start, int len)
{
if(start >= len)
return;
printf("%d ", arr[start]);

printArray(arr, start + 1, len); 
}
int main(){
int array[length]={6,4,2,9,1,7,3,10};
int x=5;
selection(array,length,x);
printArray(array,0,length);
return 0;
}

我还并没有实现递归解决方案,因为我尝试的东西总是出现分段错误,因为我在数组之外。

任何人都能在没有时间的情况下重复做这件事吗。我想你需要把阵列分开,然后把对半看

给你。

#include <stdio.h>
void partition( int a[], size_t n, int pivot )
{
if ( !( n < 2 ) )
{
if ( *a < pivot )
{
partition( a + 1, n - 1, pivot );
}
else
{
if ( *( a + n - 1 ) < pivot )
{
int tmp = *a;
*a = *( a + n - 1 );
*( a + n - 1 ) = tmp;
partition( a + 1, n - 2, pivot );
}
else
{
partition( a, n - 1, pivot );
}
}
}
}
int main(void) 
{
int a[] = { 4, 6, 2, 9, 1, 7, 3, 10 };
const size_t N = sizeof( a ) / sizeof( *a );
for ( size_t i = 0; i < N; i++ )
{
printf( "%d ", a[i] );
}
putchar( 'n' );

int pivot = 5;
partition( a, N, pivot );
for ( size_t i = 0; i < N; i++ )
{
printf( "%d ", a[i] );
}
putchar( 'n' );
return 0;
}

程序输出为

4 6 2 9 1 7 3 10 
4 3 2 1 9 7 6 10 

或者也使用函数CCD_ 1的递归定义。

#include <stdio.h>
void partition( int a[], size_t n, int pivot )
{
if ( !( n < 2 ) )
{
if ( *a < pivot )
{
partition( a + 1, n - 1, pivot );
}
else
{
if ( *( a + n - 1 ) < pivot )
{
int tmp = *a;
*a = *( a + n - 1 );
*( a + n - 1 ) = tmp;
partition( a + 1, n - 2, pivot );
}
else
{
partition( a, n - 1, pivot );
}
}
}
}
void printArray( const int a[], size_t n )
{
if ( n )
{
printf( "%d ", *a );
printArray( a + 1, n - 1 );
}
else
{
putchar( 'n' );
}
}
int main(void) 
{
int a[] = { 4, 6, 2, 9, 1, 7, 3, 10 };
const size_t N = sizeof( a ) / sizeof( *a );
printArray( a, N );     
int pivot = 5;
partition( a, N, pivot );
printArray( a, N );     
return 0;
}

递归函数printArray也可以通过以下方式定义

void printArray( const int a[], size_t n )
{
n == 0 ? ( void )putchar( 'n' ) 
: ( printf( "%d ", *a ), printArray( a + 1, n - 1 ) );
}

最新更新