[英]C kind of sorting
好的,所以 function 以這樣的方式排列數組中的元素,即所有小於給定值的元素都放置在大於給定值的元素左側的位置。
例如,如果數組內容是 {4,6,2,9,1,7,3,10} 並且 x 被指定為 5,那么 {4,3,2,1,9,7,6,10} 是一個可能的解決方案,因為所有小於 5 的元素都在大於 5 的元素的左側。
此外,除了在主 function 中定義數組外,禁止使用括號 []。
另外,實現一個打印數組內容的 function。 這兩個函數都必須遞歸實現。 您只能訪問數組的每個元素一次。
好的,所以這個“挑戰”,我不知道在給定的限制下是否可能。 我試圖用一個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;
}
我沒有實現遞歸解決方案,因為我嘗試過的事情不斷給出分段錯誤,因為我到達了數組之外。
任何人都可以在沒有 for 或 while 的情況下遞歸地執行此操作。 我想你需要拆分數組並看一半一半
給你。
#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;
}
程序 output 是
4 6 2 9 1 7 3 10
4 3 2 1 9 7 6 10
或者也可以使用 function printArray
的遞歸定義。
#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;
}
遞歸的 function printArray
也可以通過以下方式定義
void printArray( const int a[], size_t n )
{
n == 0 ? ( void )putchar( '\n' )
: ( printf( "%d ", *a ), printArray( a + 1, n - 1 ) );
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.