嗨,我編了下面的程序來輸入一個數組的數組並對其進行排序。C上的快速排序錯誤
但我仍然得到錯誤的答案,如1.3333331數字!
什麼問題?
#include <stdio.h>
void quicksort(double array[], long long left, long long right);
long long partition(double array[], long long left, long long right);
int fDig(double x);
int main(void) {
long long quantity = 0LL, counter = 0LL;
int dig = 0;
scanf("%lli", &quantity);
double beard[quantity];
for(counter = 0LL; counter < quantity; counter++) {
scanf("%lf", &beard[counter]);
}
quicksort(beard, 0LL, quantity - 1LL);
for(counter = 0LL; counter < quantity; counter++) {
dig = fDig(beard[counter]);
printf("%.*lf", dig, beard[counter]);
if(counter == quantity - 1LL) {
break;
}
printf(" ");
}
return 0;
}
int fDig(double x) {
int result = 0;
while(x != floor(x)) {
x *= 10;
result++;
}
return result;
}
/* Quick sort recursive function */
void quicksort(double array[], long long left, long long right){
if (left < right) {
long long middle = partition(array, left, right);
quicksort(array, left, middle - 1LL);
quicksort(array, middle + 1LL, right);
}
}
/* Partition :
Modifies the array :
SMALLER , PIVOT , GREATER
Returns the index for pivot because pivot is placed in the final position
*/
long long partition(double array[], long long left, long long right) {
long long middle;
double x = array[left];
long long l = left;
long long r = right;
while(l < r) {
while((array[l] <= x) && (l < right)) {
l++;
}
while((array[r] > x) && (r >= left)) {
r--;
}
if(l < r) {
double temp = array[l];
array[l] = array[r];
array[r] = temp;
}
}
middle = r;
double temp = array[left];
array[left] = array[middle] ;
array[middle] = temp;
return middle ;
}
我想對數組進行排序,因爲數組元素是浮點數最多8位小數! (現在用我正確的算法?)
什麼是輸入數據? –
有什麼問題? (即什麼是輸入和輸出) –
這是排序錯誤,或'fDig'和輸出格式?嘗試對實際輸入的最大位數進行硬編碼,然後查看會發生什麼情況。 – Useless