Below code is working for Array{ 4 5 3 7 2 }, but not working for other test case given on HackerRank Site. What is error in my code? Am I doing any wrong while merging the two array a1[] and a2[] into the ar[] ?
https://www.hackerrank.com/challenges/quicksort1
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <assert.h>
void partition(int ar_size, int * ar) {
int a1[100], a2[100];
int p = ar[0];
int i=0, j=0 , k=0;
for(i=0; i<ar_size; i++){
if(ar[i] < p)
{
a1[j] = ar[i];
j++;
}
else if(ar[i] >= p){
a2[k] = ar[i];
k++;
}
}
i=0, j=0 , k=0;
while(a1[i]){
ar[i] = a1[j];
i++;
j++;
}
while(a2[k]){
ar[i] = a2[k];
i++;
k++;
}
for(i=0; i<ar_size; i++){
printf("%d ", ar[i]);
}
}
int main(void) {
int _ar_size;
scanf("%d", &_ar_size);
int _ar[_ar_size], _ar_i;
for(_ar_i = 0; _ar_i < _ar_size; _ar_i++) {
scanf("%d", &_ar[_ar_i]);
}
partition(_ar_size, _ar);
return 0;
}
答案 0 :(得分:0)
int _ar_size;
scanf("%d", &_ar_size);
int _ar[_ar_size], _ar_i;
初始化变量或数组时,无法初始化数字未知的数组。您应该知道需要多少(如果您不知道所需的大小,只需使用大数字初始化数组或使用链表) 因为电脑或者其他什么应该知道他将在内存中分配多少。
答案 1 :(得分:0)
删除i = 0,j = 0,k = 0;以下是什么,并尝试以下
while(k--){
ar[k+j] = a2[k];
}
while(j--){
ar[j] = a1[j];
}